<?php 
/**
 * bug Fix registered Done on 030514

 */
class RosterController extends Zend_Controller_Action
{
	const COME_EARLY_NORMAL_LIMIT = 5;//5
	const COME_REALLY_EARLY_LIMIT = 30;//30
	const COME_LATE_NORMAL_LIMIT = 5;//5
	
	const LEAVE_EARLY_NORMAL_LIMIT = 5;//5
	const LEAVE_REALLY_LATE_LIMIT = 30;//30
	/**
	 *  event Code
	 */
		
    public function init(){
    /**
	 *
	 *
	 */    
	
	}

    public function indexAction(){
	
		//echo "shomething";	
 
	}

	/**
	 * This one is for staff to setup their own password
	 */
	public function setupAction(){
		
		//echo $_SERVER['HTTP_USER_AGENT'] . "<br />";
		$sDetail = new Model_DbTable_Roster_Stafflogindetail();
		$oldPwd = new Model_System_Oldpwd();
		
		$this->view->ifMobile = true;
		$this->view->showFirst = true;
		$this->view->showSecond = false;
		$this->view->userID = 0;
		$this->view->passwordChecked = false;
		$this->view->passwordAftercheck = "";
		$this->view->fullName = "";
		$errorFlag = false;
		
		$browser = get_browser(null, true);

		//var_dump($browser);
		
		if($browser['platform'] =="Win7" || $browser['platform'] =="WinXP" || $browser['platform'] =="unknown" ){
			$this->view->ifMobile = false;	
		if($_POST){	
			//var_dump($_POST);
		if(isset($_POST["btn_setup_password"]) && $_POST["btn_setup_password"]=="Setup My Password" ){
			
			$firstName = $sDetail->formatName($_POST["first_name"]);
			$lastName = $sDetail->formatName($_POST["last_name"]);
			
			$dob = $sDetail->formateDob($_POST["year"],$_POST["month"],$_POST["day"]);
			
			$fullName = $firstName." ".$lastName;
			$this->view->fullName = $fullName;
			
			$fullNameAfter = Model_EncryptHelper::sslPassword($fullName);
			
			$dobAfter = Model_EncryptHelper::sslPassword($dob);
			
			//d($fullNameAfter,$dobAfter,$dob);
			
			$result = $sDetail->checkNameandDob($fullNameAfter, $dobAfter);
		
			if($result){
				$this->view->showFirst = false;
				$this->view->showSecond = true;
				$this->view->userID = $result;
				
			}else{
				$errorFlag = true;
				$this->view->errorMessage = "Infomation does not match";
			}
			
			
		}
		if(isset($_POST["btn_check_password"]) && $_POST["btn_check_password"]=="Check My Password" ){
		
			$password = $_POST["password"];
			$confirm = $_POST["password_confirm"];
			$this->view->userID = $_POST["user_id"];
			$this->view->passwordAftercheck = $_POST["password"];
			
			if($password != $confirm){
				$errorFlag = true;
				$this->view->errorMessage = "Password did not match the confirmation!!";	
				
			}			
			
			if(strlen($password)<8){
				$errorFlag = true;
				$this->view->errorMessage .= "Password Length not long enough<br/>";
			}
			
			if(!preg_match('/[A-Z]/',$password)){
				$errorFlag = true;
				$this->view->errorMessage .= "Password much contain at least one UPPER case<br/>";
			}			
			if(!preg_match('/[a-z]/',$password)){
				$errorFlag = true;
				$this->view->errorMessage .= "Password much contain at least one lower case<br/>";
			}
			if(!preg_match('/[0-9]/',$password)){
				$errorFlag = true;
				$this->view->errorMessage .= "Password much contain at least one number<br/>";
			}
			
			if(!$sDetail->checkPdUnique(Model_EncryptHelper::hashsha($password))){
				$errorFlag = true;
				$this->view->errorMessage .= "Password strength not good enough,Please use stronger password and try again <br/>";					
			}	
			if($oldPwd->matchingPwd(Model_EncryptHelper::hashsha($password))){
				
				$errorFlag = true;
				$this->view->errorMessage .= "Password strength not good enough,Please DO-NOT use any of your previous password  <br/>";
			}
			
			//if password find match say sorry , if not redirect to doneS
			
			if($errorFlag){
				
				$this->view->errorFlag = true;
				$this->view->showFirst = false;
				$this->view->showSecond = true;
			}
			else{
				
				$this->view->errorFlag = false;
				$this->view->showFirst = false;
				$this->view->showSecond = true;
				$this->view->passwordChecked = true;
				//$this->view->							
			}
		
		}		
		if(isset($_POST["btn_record_password"]) && $_POST["btn_record_password"]=="Password Checked, Now Save It" ){
				
			
			$userId = $_POST["user_id"];
			//$passwords = $_POST["password_aftercheck"];
			$passwordAfters = Model_EncryptHelper::hashsha($_POST["password_aftercheck"]);
			$sDetail->updatePassword($userId, $passwordAfters);
			//if password find match say sorry , if not redirect to done	
			$this->_helper->redirector("setup-done");
					 
		}		
		}	
			
		}
		else{
			
			$this->view->ifMobiel = true;
			$this->view->errorFlag = true;
			$this->view->errorMessage = "You are using the Mobile Phone to login in Or using Latest Version of Firefox which are not supported";	
		}
		
	}
	/**
	 * Setup Done , show the tutorial Link
	 */
	public function setupDoneAction(){
		
	}
	
	public function inputAction(){
		$stfDeatail = new Model_DbTable_Roster_Stafflogindetail();
		$stfList = $stfDeatail->listStaff();
		$this->view->sList = $stfList;
		$this->view->show = 'yes';
	}
	
	
	public function deleteStaffAction(){
		$stfDeatail = new Model_DbTable_Roster_Stafflogindetail();
		$stfInfo = new Model_DbTable_Roster_Staffinfo();
		
		$stfList = $stfDeatail->listStaff();
		$leaveList = array();
		$activeList = array();
		foreach ($stfList as $k => $v){
			if($v['a'] == 9){
				$leaveList[] = $v;
			}else{
				$activeList[] = $v;
			}
		}
		
		$this->view->sList = $activeList;
		$this->view->lList = $leaveList;
		
		if(isset($_POST['submit'])){
			$password = $stfDeatail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST["password"])));
			
			if($password['id'] == '110'){
				foreach ($_POST['delete'] as $k => $v){
					$stfDeatail->deleteStaff($v);
					$stfInfo->deleteStaffinfo($v);
				}	
			}else{
				foreach ($_POST['delete'] as $k => $v){
					d($v);
				}
			}
		}
	}
	/**
	 * embed in the company home App page
	 * this one also need to move to the website 
	 */
	public function loginAction(){
		
		$this->view->errorFlag = false;
		$shopHead = $this->_getParam('shop');
		$this->view->shopHead = $shopHead;
		
		$token =(isset($_GET["token"]))?$_GET["token"]:"";
		$mail = new Model_Emailshandler();
	
		
		$sDetail = new Model_DbTable_Roster_Stafflogindetail();
		$sL = new Model_DbTable_Shoplocation();
		$tokenCheck = $sL->getToken($shopHead);
		
			$ip = $_SERVER['REMOTE_ADDR'];
		$browser = get_browser(null, true);
		
		//var_dump($browser);
		
		if(!($browser['platform'] =="Win7" || $browser['platform'] =="WinXP" || $browser['platform'] =="unknown" )){
			
			$this->view->errorFlag = true;
			
			$this->view->errorMessage = "Attempt to login on Mobile Device, the record has been send to Administrator";
			
			$mail->sendNormalEmail("eco3@phonecollection.com.au","Attempt Login On Mobile Device",$ip.$shopHead);
			
		}
		
		if(trim($token)!=(trim($tokenCheck))){
			
			$this->view->errorFlag = true;
			
			$this->view->errorMessage = "Login failed, the record has been send to Administrator";
			
			$mail->sendNormalEmail("eco3@phonecollection.com.au","Token Fail On Login",$ip.$shopHead);
		}
		
		if($_POST){
			
			$stLine = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST["password"])));
			
			if(!$stLine){
				
				$this->view->errorFlag2 = true;
				
				//$mail->sendNormalEmail("eco1@phonecollection.com.au","Pasword Check Fail During Login",$ip.$shopHead);

				$this->view->errorMessage = "Login unsuccess, The Password Check Failed, You May Try unlimited Times";
					
			}
			else{
				
				if(date("U",strtotime($stLine['expire_date'])) < date("U",strtotime(Model_DatetimeHelper::dateToday()))){
					$this->view->errorFlag = true;
					
					$mail->sendNormalEmail("office5@phonecollection.com.au","Expire Staff Try Login",$ip.' '.$shopHead.' '.$stLine['ni']);
					
					$this->view->errorMessage = "<h1>Don't panic, Your Password Has Been Blocked</h1>
					you password will be blocked if you did not submit you paper document within 7 days to head office.<br />
					it is possible that you have already been send the documents to the head office, if that is the case <br />
					Please Contact Head Office Immediately , we can unlock it in one mins.<br />
					If you still need some time to prepare the documents , we will also happy to extended the expire date,<br />
					please contact headOffice (Alice) ASAP.
					";					
					
				}
				else{
					$std = Model_EncryptHelper::sslPassword(trim($stLine["id"]));
					
					$arrPar = array(
							"token" => urlencode($token),
							"std" =>urlencode($std)
					);
					echo $arrPar['token'];
					$this->_helper->redirector("on-off-duty","roster",null,$arrPar);					
					
				}
				

			}
				
		}		
		
	}
	/**
	 * After login , the staff can now change the status
	 * the view page has been change 
	 */
	public function onOffDutyAction(){
		
		$sL = new Model_DbTable_Shoplocation();	
		$token = urldecode($this->_getParam("token"));
		$std = Model_EncryptHelper::getSslPassword(urldecode($this->_getParam("std")));
		$record = new Model_DbTable_Roster_Attnrecord();
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$leave = new Model_Hr_Staffleave();
		
		$mail = new Model_Emailshandler();
		$ip = $_SERVER['REMOTE_ADDR'];
		$browser = get_browser(null, true);
		$dateToday = Model_DatetimeHelper::dateToday();
		//$pv = $this->_getParam("pv");
		$leaveApplication = $leave->getApproveLeaveByIdDate($std, $dateToday);
		
		//var_dump($browser);
		
		if(!($browser['platform'] =="Win7" || $browser['platform'] =="WinXP")){
				
			$this->view->errorFlag = true;
				
			$this->view->errorMessage = "Attempt to login on Mobile Device, the record has been send to Administrator";
				
			$mail->sendNormalEmail("eco3@phonecollection.com.au","Attempt By Pass Login On Mobile",$ip."|".$token."|".$std);
				
		}
		
		if($token!="" && $std!=""){
		$shopHead = $sL->getShopHeadByToken($token);
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();	

			date_default_timezone_set('Australia/Melbourne');
		
		if($shopHead == "ADPC" || $shopHead == "WLIC" || $shopHead == "CLPC" ||$shopHead == "CLIC" ){

			date_default_timezone_set('Australia/Adelaide');
		}
		
		$dateBeginToday = date("U",strtotime(date("Y-m-d")));
		
	
		
		$row = $stDetail->getDetail($std);
		
		
		$result = $record->getLastStatus($std);

		$onOffDuty = date("D, d M Y H:i:s",$result["ti"]);

		$this->view->firstLoginToday = (bool)($result["ti"] < $dateBeginToday); 
		
		$this->view->leaveCheck = $leaveApplication;
		$this->view->onOffDuty = $onOffDuty;
		$this->view->stID = $std;
		$this->view->staffName = Model_EncryptHelper::getSslPassword($row["n"]);
		$this->view->shopHead = $shopHead;
		$birthday = Model_EncryptHelper::getSslPassword($row["d"]);
		$bCom = date("m-d",$birthday);
		$todayCom = date("m-d");
		//var_dump($bCom,$todayCom);
		$this->view->birthday = false;
		if($bCom == $todayCom){
			//echo "tre";
			$this->view->birthday = true;
		}  
		
		// if expire 
		$expireDate = $row['expire_date'];
		$dateToExp = (int)(date("U",strtotime($expireDate)) - date("U",strtotime($dateToday)))/86400;

			$this->view->aboutExpire = $dateToExp;
		
		if($_POST){
			
			$intShiftBegin = date("U" ,strtotime($dateToday." ".$_POST["shift_start_hour"].":".$_POST["shift_start_min"]));
			$intShiftEnd = date("U" ,strtotime($dateToday." ".$_POST["shift_end_hour"].":".$_POST["shift_end_min"]));
			
			$idSheet = $_POST["id_sheet"];
			$tSheet->updateTimesheet($idSheet,$std,$shopHead,$intShiftBegin, $intShiftEnd);
			
		
			$sLoc = new Model_DbTable_Shoplocation();
			$stDeail = new Model_DbTable_Roster_Stafflogindetail();
			$stLine = $stDeail->getDetail($std);
				
			$staffName = Model_EncryptHelper::getSslPassword($stLine["n"]);
			$NickName = $stLine["ni"];
				
				
			$shopMgrEmail = $sLoc->getStoreManMailByHead($shopHead);
			$shopAreaEmail = $sLoc->getAreaManMailByHead($shopHead);
			if($shopMgrEmail==""){
				$mail->sendShiftChangeEmail($shopAreaEmail, $staffName."(".$NickName.")",$_POST["shift_start_hour"].":".$_POST["shift_start_min"],$_POST["shift_end_hour"].":".$_POST["shift_end_min"],$shopHead);
			}
			else{
				$mail->sendShiftChangeEmail($shopMgrEmail, $staffName."(".$NickName.")",$_POST["shift_start_hour"].":".$_POST["shift_start_min"],$_POST["shift_end_hour"].":".$_POST["shift_end_min"],$shopHead);
			}
				
			echo '<script language="javascript">alert("Shift Change Email Sent To Your Manager");</script>';
		}
		
		$shiftToday = $tSheet->listShiftByStaffIdToday($std, $shopHead);
		$this->view->shiftToday = $shiftToday;
		
		}
		else{
			$this->view->errorFlag = true;
			
			$this->view->errorMessage = "Attempt to login fail, the record has been send to administrator";
			
			$mail->sendNormalEmail("eco3@phonecollection.com.au","Attempt By Pass Login ,Token Or Std Fail",$ip."|".$token."|".$std);			
			
			
		}
		
		//var_dump($row);
		
			if($std==1){
				$this->renderScript('/roster/on-off-duty-20140604.phtml');
			}
			else{
				$this->renderScript('/roster/on-off-duty-new.phtml');
			}
		
			
		
	}
	/**
	 * Save the record and show the result to user
	 */
	public function onOffDutyRecordAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		$mail = new Model_Emailshandler();
		$ip = $_SERVER['REMOTE_ADDR'];
		$browser = get_browser(null, true);
		$record = new Model_DbTable_Roster_Attnrecord();
		$eventRecord = new Model_DbTable_Roster_Earlylateevent();
		$timeSheet = new Model_DbTable_Roster_Timesheet();
		$eventTime = "";
		$dateToday = Model_DatetimeHelper::dateToday();
		$dateThisMonday = Model_DatetimeHelper::getThisWeekMonday();
		
		$needExplainOnDuty = true;
		$needExplainOffDuty = true;
		$needBreakOffDuty = true;
		
		//var_dump($browser);
		
		if(!($browser['platform'] =="Win7" || $browser['platform'] =="WinXP")){
		
			$this->view->errorFlag = true;
		
			$this->view->errorMessage = "Attempt to login on Mobile Device, the record has been send to Administrator";
		
			$mail->sendNormalEmail("eco3@phonecollection.com.au","Attn Login Fail",$ip);
		
		}
				
		if($_POST){

			$staffId = $_POST["std"];
			$this->view->staffId = $staffId; 
			
			$shopHead = Model_EncryptHelper::sslPassword(trim($_POST["shophead"]));
		if(trim($_POST["shophead"]) == "ADPC" || trim($_POST["shophead"]) == "WLIC" || trim($_POST["shophead"]) == "CLPC" || trim($_POST["shophead"]) == "CLIC" ){

			date_default_timezone_set('Australia/Adelaide');
			
		}
			$eventTime = date("U");
			
			$status = 1;
			$lastStatus = 1;
			

			
			
			if(isset($_POST["btn_on_duty"]) && $_POST["btn_on_duty"] =="Click Me On Duty" ){
				
				$encodedData = base64_decode($_POST['img_data']);
				$fileName = getcwd()."/attn_images/".$_POST['img_name'].".jpg";
				@file_put_contents($fileName, $encodedData);
				
				if(isset($_POST['id_shift']) && $_POST['id_shift']!=""){
					$timeSheet->staffLogin($_POST['id_shift']);
				}
				$status = $record->createStatusOnDuty();
				$record->addRecord($staffId, $eventTime, $ip, $shopHead, $status,$_POST['img_name']);
				$this->view->message = "Status Change Success,Click Link below return to Login Page Again";
				$this->view->eventTime = $eventTime;
				$lastStatus = 1;
				
			}// if on duty
			
			if(isset($_POST["btn_off_duty"]) && $_POST["btn_off_duty"] =="Click Me Off Duty" ){
				
				$encodedData = base64_decode($_POST['img_data']);
				$fileName = getcwd()."/attn_images/".$_POST['img_name'].".jpg";
				@file_put_contents($fileName, $encodedData);
				
				
				$status = $record->createStatusOffDuty();
				$record->addRecord($staffId, $eventTime, $ip, $shopHead, $status,$_POST['img_name']);
				$this->view->message = "Status Change Success,Click Link below return to Login Page Again";
				$this->view->eventTime = $eventTime;
				$lastStatus = 2;
				
				
					
			}

			if(isset($_POST["btn_save_shift"]) && $_POST["btn_save_shift"] =="Save" ){
								
				
				
				$shiftBeginStr = $dateToday." ".$_POST['shift_start_hour'].":".$_POST['shift_start_min'].":"."00";
				$shiftEndStr = $dateToday." ".$_POST['shift_end_hour'].":".$_POST['shift_end_min'].":"."00";
				
				$intShiftBegin = date("U",strtotime($shiftBeginStr));
				$intShiftEnd = date("U",strtotime($shiftEndStr));
				$lastStatus = $_POST["on_off_status"];
				
				// show the warning 
				if(($intShiftEnd - $intShiftBegin) > 18000){
					
					$this->view->showBreakMessage = true;
				}
				else{
					$this->view->showBreakMessage = false;
				}
				
				// change the show time for adelaide 
				
				if($_POST["shophead"]=="ADPC" || $_POST["shophead"]=="CLPC" || $_POST["shophead"]=="WLIC" || $_POST["shophead"]=="CLIC"){
					
					//$intShiftBegin += 1800;
					//$intShiftEnd += 1800;
				
				}
				//check exist 
				if(!$timeSheet->searchTimeSheet($_POST["std"],$_POST["shophead"], $intShiftBegin, $intShiftEnd)){
				
					$timeSheet->addTimesheet($_POST["std"],$_POST["shophead"], $intShiftBegin, $intShiftEnd,1);
				
				}
			}// if btn save 
			if(isset($_POST["btn_event_explain"]) && $_POST["btn_event_explain"] =="Save" ){
				// save the event 
				$idEvent = $eventRecord->addEarlylateevent($_POST["std"],$_POST["come_really_early_time"],START_REALLY_EARLY,"POSITIVE |".$_POST["staff_comment"]);
				$timeSheet->updateOnDutyEvent($_POST["id_timesheet"], $idEvent);
				
				$needExplainOnDuty = false;
				$lastStatus = 1;
			}// if save morning explain 
			
			if(isset($_POST["btn_break_time"]) && $_POST["btn_break_time"] =="Save" ){
				// save the event on condition 
				if(isset($_POST["ind_leave_early"])){

					$idEvent = $eventRecord->addEarlylateevent($_POST["std"], $_POST["time_leave_event"],FINISH_EARLY,"NEGATIVE |".$_POST["staff_comment"]);
					$timeSheet->updateOffDutyEvent($_POST["id_timesheet"], $idEvent);
				
				}
				if(isset($_POST["ind_leave_late"])){

					$idEvent = $eventRecord->addEarlylateevent($_POST["std"], $_POST["time_leave_event"],FINISH_REALLY_LATE,"POSITIVE |".$_POST["staff_comment"]);
					$timeSheet->updateOffDutyEvent($_POST["id_timesheet"], $idEvent);						
						
				}
				// add break time 
					$timeSheet->updateBreakTime($_POST["id_timesheet"],$_POST["break_time"]);
				
				$needExplainOffDuty = false;
				$needBreakOffDuty = false;
				$lastStatus = 2;
				
			}// if save morning explain			
			
			//var_dump($staffId, $dateToday,$_POST["shophead"]);
			
			$statusLine = $record->getFirstOnLastOffDuty($staffId, $dateToday,Model_EncryptHelper::sslPassword($_POST["shophead"]));
			$todayTimeSheet = $timeSheet->listShiftByStaffIdToday($staffId,$_POST["shophead"]);
			
			//var_dump($statusLine);
			//var_dump($todayTimeSheet);
			//var_dump($lastStatus);
			
			if($todayTimeSheet){
				$this->view->timeSheetID = $todayTimeSheet["id_sheet"];
				if($lastStatus == 1){
						$this->view->needExplainOff = false;
						$this->view->needBreakOff = false;
				// on duty ,compare with the first On duty today, this time may not be the first time  	
					$intShiftBegin = $todayTimeSheet["shift_begin"];
					$intFistOn = $statusLine[0];
					//echo "Shift Begin";
					//echo ($intFistOn - $intShiftBegin);
					
					if((($intFistOn - $intShiftBegin) < - (self::COME_EARLY_NORMAL_LIMIT * 60)) && (($intFistOn - $intShiftBegin) > - (self::COME_REALLY_EARLY_LIMIT * 60))) {
						$this->view->needExplainOn = false;			
					//record
						$idEvent = $eventRecord->addEarlylateevent($staffId,$intFistOn,START_EARLY,"POSITIVE");
						$timeSheet->updateOnDutyEvent($todayTimeSheet["id_sheet"], $idEvent);						
					}
					if(($intFistOn - $intShiftBegin) <= - (self::COME_REALLY_EARLY_LIMIT * 60)){
						// need Explain
						//echo "NEED EXP ON".$needExplainOnDuty;
						$this->view->needExplainOn = $needExplainOnDuty;
						$this->view->comeReallyEarlyTime = $intFistOn;
						$this->view->timeSheetID = $todayTimeSheet["id_sheet"];
							
					}
					if(($intFistOn - $intShiftBegin) > (self::COME_LATE_NORMAL_LIMIT * 60)){
							$countLateToday = $eventRecord->getLateEvent($staffId, $dateToday, $dateToday); 
						if(!$countLateToday){
							$idEvent = $eventRecord->addEarlylateevent($staffId,$intFistOn,START_LATE,"NEGATIVE");
							$timeSheet->updateOnDutyEvent($todayTimeSheet["id_sheet"],$idEvent);
						// attn to manager
						}
						$this->view->needExplainOn = false;
						
						$countLate = $eventRecord->getLateEvent($staffId, $dateThisMonday, $dateToday);
						
						if($countLate>2){
							$mail = new Model_Emailshandler();
							$sLoc = new Model_DbTable_Shoplocation();
							$stDeail = new Model_DbTable_Roster_Stafflogindetail();
							$stLine = $stDeail->getDetail($staffId);
							
							$staffName = Model_EncryptHelper::getSslPassword($stLine["n"]);
							$NickName = $stLine["ni"];
							
							
							$shopMgrEmail = $sLoc->getStoreManMailByHead(trim($_POST["shophead"]));
							$shopAreaEmail = $sLoc->getAreaManMailByHead(trim($_POST["shophead"]));
							if($shopMgrEmail==""){
								$mail->sendLateEmail($shopAreaEmail, $staffName."(".$NickName.")");
							}
							else{
								$mail->sendLateEmail($shopMgrEmail, $staffName."(".$NickName.")");
							}	
							
							//echo "Mail Sent";
							//$mail->sendLateEmail($managerEmail, $staffName);
						}
						
						$this->view->notifyManager = true; 
						$this->view->lateTime = $countLate;		
							
			
						}
					}
					
					
				// early , really early 

				// late really late 
				if($lastStatus == 2){
					$this->view->needExplainOn = false;
				//Last off duty time , which is just happened 
					$intShiftEnd = $todayTimeSheet["shift_end"]; 	
					$intLastOff = $statusLine[1];
					$this->view->timeLeaveEvent = $intLastOff;
					
					if(($intLastOff -$intShiftEnd) <-(self::LEAVE_EARLY_NORMAL_LIMIT * 60) ){
						
						// need explain 
						$this->view->timeSheetID = $todayTimeSheet["id_sheet"];
						$this->view->needExplainOff = $needExplainOffDuty;
						$this->view->leaveEarlyNormal = true;
						$this->view->leaveReallyLate = false;
					}
					
					if(($intLastOff -$intShiftEnd) > (self::LEAVE_REALLY_LATE_LIMIT * 60)){
						
						//need explain
						$this->view->timeSheetID = $todayTimeSheet["id_sheet"];
						$this->view->needExplainOff = $needExplainOffDuty;
						$this->view->leaveEarlyNormal = false;
						$this->view->leaveReallyLate = true;						
					}
				
				//here Ask if the break time 
				
					$this->view->needBreakOff = $needBreakOffDuty;

				}

			}// time sheet 
				
		
			
			//Does Not matter which button clicked , need to calculate 
			
			//check the recent status 
			//check today time sheet Ready 
			
			//who is triging on? post status is ON , or transfered by save status   
			
			//off is triging off post status is Off , or trnasfered by Save Status
			
			
			
			$this->view->message = "Status Change Success,Click Link below return to Login Page Again";
			$shiftRecord = $timeSheet->listShiftByStaffIdToday($_POST["std"],$_POST["shophead"]);			
			$this->view->shiftRecord = $shiftRecord;
			
			
			//echo "ONOFFBREAK";
			//var_dump($shiftRecord,$needExplainOnDuty,$needExplainOffDuty,$needBreakOffDuty);
			
			
		}//If Post 
		else{

			$this->view->errorFlag = true;
			$this->view->errorMessage = "Access this page Incorrectly";
			
		}
	}
	
	/**
	 * =================================================================================
	 *  This part is for Roster Function , not for attendance function 
	 * ================================================================================= 
	 */
	
	
	/**
	 * this is single week roster arrange v 2014 which has normal working hour and 
	 * trainning working hours
	 */
	
	public function onlineRosterV2014Action(){
		$leave = new Model_Hr_Staffleave();
		$stf = new Model_DbTable_Roster_Staffinfo();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		if(isset($_POST["btn_roster"])){
		
			$spList = $_POST["shop_selection"];
			$dateBegin = $_POST["date_begin"];
			$dateEnd = $_POST['date_end'];
				
			$arrStr = base64_encode(serialize($spList));
				
				
				
			$token  = Model_DatetimeHelper::tranferToInt($dateBegin);
				
			$shopCounts = count($spList);
				
			$dateDiff = Model_DatetimeHelper::dateDiff($dateEnd, $dateBegin);
				
		
			if($dateBegin <= Model_DatetimeHelper::dateToday()){
		
				$this->_redirect("/roster/online-roster-confirm/shops/".$arrStr."/token/".$token."/db/".$dateBegin);
			}
			else{
				if($shopCounts == 1 && $dateDiff >7 && $dateEnd!=""){
		
					$this->_redirect("/roster/online-roster-v2014/shops/".$arrStr."/token/".$token."/db/".$dateBegin."/dn/".$dateEnd);
				}
				else{
						
					$this->_redirect("/roster/online-roster-v2014/shops/".$arrStr."/token/".$token."/db/".$dateBegin);
				}
					
					
			}
		
		
		}
		
		$shops = $this->_getParam("shops");
		$dateBegin = $this->_getParam("db");
		$token = $this->_getParam("token");
		$val = $this->_getParam("su");
		
		
		$this->view->su = isset($val)?$val:"normal";
		
		$this->view->shops = $shops;
		$this->view->dateBegin = $dateBegin;
		
		date_default_timezone_set('Australia/Melbourne');
		$dateCheck = date("Y-m-d",$token);
		
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$this->view->stList = $stDetail->listStaffByNickName();
		$arrResult = array();
		
		if($dateCheck == $dateBegin){
		
			$shopList = unserialize(base64_decode($shops));
			$this->view->spList = $shopList;
			$dateEnd = Model_DatetimeHelper::adjustDays("add", $dateBegin, 6);
			$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
			$this->view->arrDate = $arrDate;
			foreach($shopList as $shopKey => $shopHead){
		
				foreach($arrDate as $dateKey => $dateValue){
					//var_dump($shopHead,$dateValue);
					$arrResult[$shopKey][$dateKey] = $tSheet->listArrangedShiftByDateByShopWithFormat($shopHead, $dateValue, $dateValue);
						
				}
			}
			
		}//end of date begin
		
		if($_POST){
			//d($_POST);
				
			if(isset($_POST["arr_Detail"])){
					
				foreach($shopList as $shopKey => $shopHead){
						
					foreach($arrDate as $dateKey => $dateValue){
							
						//var_dump($shopHead,$dateValue);
						if(isset($_POST["arr_Detail"][$shopKey][$dateKey])){
							$arrResult[$shopKey][$dateKey] = $_POST["arr_Detail"][$shopKey][$dateKey];
						}
						else{
							$arrResult[$shopKey][$dateKey] = "";
						}
					}
						
				}
			
			}//end of arr_detail
				
			if(isset($_POST['recal'])){
				foreach($shopList as $shopKey => $shopHead){
				
					foreach($arrDate as $dateKey => $dateValue){
							
						//var_dump($shopHead,$dateValue);
						if(isset($_POST["arr_Detail"][$shopKey][$dateKey])){
							$arrResult[$shopKey][$dateKey] = $_POST["arr_Detail"][$shopKey][$dateKey];
						}
						else{
							$arrResult[$shopKey][$dateKey] = "";
						}
					}
				
				}
				foreach ($arrResult as $k => $v){
					foreach ($v as $k2 => $v2){
						if(!empty($v2)){
							foreach ($v2 as $k3 => $v3){
					
								//$tSheet->updateBreakTime2($v3[5],$v3[6]);
							}
						}
					}
				}
			}
			
			// add button
			//var_dump($arrResult);
				
			if(isset($_POST["btn_addto"])){
					
					
				$arrDailyTmp = array();
					
				for($i=1;$i<=3;$i++){
					$str = "staff_name_".$i;
					if($_POST[$str]!==""){
						$breakTime = 0;
						$totalHours = round(($_POST["shift_end_hour_".$i] - $_POST["shift_start_hour_".$i]) + ($_POST["shift_end_min_".$i] - $_POST["shift_start_min_".$i])/60,2);
		
						if($totalHours >=5){
							$breakTime = 30;
							$totalHours -= 0.5;
						}
						if($totalHours >=9){
							$breakTime = 60;
							$totalHours -= 1;
						}
						$arrDailyTmp[] = array($_POST[$str],$_POST["shift_start_hour_".$i],$_POST["shift_start_min_".$i],$_POST["shift_end_hour_".$i],$_POST["shift_end_min_".$i],"new".date("U").$i,$breakTime,$totalHours,0);
					}
				}
				//var_dump($arrDailyTmp);
				$counter = 0;
				foreach($_POST["choice"] as $theShop => $dates ){
						
					foreach($dates as $theDate => $value){
						if(isset($arrDailyTmp[0][0])){
							$arrDailyTmp[0][5] .= $counter;
							$stdId1 = $arrDailyTmp[0][0];
							$counter++;
						}
						if(isset($arrDailyTmp[1][0])){
							$arrDailyTmp[1][5] .= $counter;
							$stdId2 = $arrDailyTmp[1][0];
							$counter++;
						}
						if(isset($arrDailyTmp[2][0])){
							$arrDailyTmp[2][5] .= $counter;
							$stdId3 = $arrDailyTmp[2][0];
							$counter++;
						}
						if($value){
							$leaveDate = $_POST['pickDate'][$theShop][$theDate];
							$check1 = false;
							$check2 = false;
							$check3 = false;
							if(!empty($stdId1)){
								$leaveCheck1 = $leave->getApproveLeaveByIdDate($stdId1, $leaveDate);
								if(!empty($leaveCheck1)){
									$check1 = true;
								}
							}
							if(!empty($stdId2)){
								$leaveCheck2 = $leave->getApproveLeaveByIdDate($stdId2, $leaveDate);
								if(!empty($leaveCheck2)){
									$check2 = true;
								}
							}
							if(!empty($stdId3)){
								$leaveCheck3 = $leave->getApproveLeaveByIdDate($stdId3, $leaveDate);
								if(!empty($leaveCheck3)){
									$check3 = true;
								}
							}
							if($check1 == true){
								$errFlag = true;
								$stfName = $stf->getStaffinfo($leaveCheck1['id_staff']);
								$stfNi = $stfDetail->getDetail($leaveCheck1['id_staff']);
								$name = $stfName['first_name']." ".$stfName['last_name'];
								$nickName = $stfNi['ni'];
								$stfLeaveDate = $leaveCheck1['period_start'];
									
								$content = "Staff (".$nickName.") ". $name ." has apply leave on ".$stfLeaveDate;
								echo "<script language='javascript'> alert('$content');</script>";
									
							}
							if($check2 == true){
								$errFlag = true;
								$stfName2 = $stf->getStaffinfo($leaveCheck2['id_staff']);
								$stfNi2 = $stfDetail->getDetail($leaveCheck2['id_staff']);
								$name2 = $stfName2['first_name']." ".$stfName2['last_name'];
								$nickName2 = $stfNi2['ni'];
								$stfLeaveDate2 = $leaveCheck2['period_start'];
								$content2 = "Staff (".$nickName2.") ". $name2 ." has apply leave on ".$stfLeaveDate2;
								echo "<script language='javascript'> alert('$content2');</script>";
							
							}
							
							if($check3 == true){
								$errFlag = true;
								$stfName3 = $stf->getStaffinfo($leaveCheck3['id_staff']);
								$stfNi3 = $stfDetail->getDetail($leaveCheck3['id_staff']);
								$name3 = $stfName3['first_name']." ".$stfName3['last_name'];
								$nickName3 = $stfNi3['ni'];
								$stfLeaveDate3 = $leaveCheck3['period_start'];
								$content3 = "Staff (".$nickName3.") ". $name3 ." has apply leave on ".$stfLeaveDate3;
								echo "<script language='javascript'> alert('$content3');</script>";
							
							}
							
							

							//var_dump($arrResult[$theShop][$theDate]);
							if(empty($arrResult[$theShop][$theDate])){
								$arrDailyTmpRes2= array();
								foreach($arrDailyTmp as $key => $tmp){
									$staffID = $tmp[0];
									if(!empty($stdId1)){ //check staff1 annual leave
										if($staffID == $stdId1){
											if(!$check1){
												$arrDailyTmpRes2[] = $tmp;
											}
										}
									}
									if(!empty($stdId2)){ //check staff2 annual leave
										if($staffID == $stdId2){
											if(!$check2){
												$arrDailyTmpRes2[] = $tmp;
											}
										}
									}
									if(!empty($stdId3)){ //check staff3 annual leave
										if($staffID == $stdId3){
											if(!$check2){
												$arrDailyTmpRes2[] = $tmp;
											}
										}
									}
								}
								
								$arrResult[$theShop][$theDate] = $arrDailyTmpRes2;
							}
							else{
								$arrDailyTmpRes = array();
								foreach($arrDailyTmp as $key => $tmp){
									
							
		
									$staffID = $tmp[0];
									$startHour = $tmp[1];
									$startmin = $tmp[2];
										
									$errFlag = false;
										
									foreach($arrResult[$theShop][$theDate] as $resKey => $v){
										if($v[0] == $staffID && ( ($v[3]*100 +$v[4]) > ($startHour*100 + $startmin) )){
											$errFlag = true;
											echo "<script language='javascript'> alert('Duplicated Enty Entered! Will not Accept');</script>";
											//break;
										}
									}
									
									if(!empty($stdId1)){ //check staff1 annual leave
										if($staffID == $stdId1){
											if(!$errFlag && !$check1){
												$arrDailyTmpRes[] = $tmp;
											}
										}
									}
									if(!empty($stdId2)){ //check staff2 annual leave
										if($staffID == $stdId2){
											if(!$errFlag && !$check2){
												$arrDailyTmpRes[] = $tmp;
											}
										}
									}
									if(!empty($stdId3)){ //check staff3 annual leave
										if($staffID == $stdId3){
											if(!$errFlag && !$check2){
												$arrDailyTmpRes[] = $tmp;
											}
										}
									}
								}
		
								$arrResult[$theShop][$theDate] = array_merge($arrResult[$theShop][$theDate],$arrDailyTmpRes);
		
							}
							
						}
							
					}
		
				}
					
			}
		
		}// End of post
		
		$this->view->arrResultLive = $arrResult;
		
	}
	
	/**
	 * New Arrange/Confirm Roster system
	 */
	public function onlineRosterV2015Action(){
		$leave = new Model_Hr_Staffleave();
		$stf = new Model_DbTable_Roster_Staffinfo();
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		date_default_timezone_set('Australia/Melbourne');
	
		if(isset($_POST["btn_roster"])){
	
			$spList = $_POST["shop_selection"];
			$dateBegin = $_POST["date_begin"];
	
			$arrStr = base64_encode(serialize($spList));

			$token  = Model_DatetimeHelper::tranferToInt($dateBegin);
			$dateEnd = Model_DatetimeHelper::adjustDays('add', $dateBegin, 6);
	
			$shopCounts = count($spList);

			if($dateEnd < Model_DatetimeHelper::dateToday()){
	
				$this->_redirect("/roster/online-roster-confirm2015/shops/".$arrStr."/token/".$token."/db/".$dateBegin);
			}
			else{
				
				$this->_redirect("/roster/online-roster-v2015/shops/".$arrStr."/token/".$token."/db/".$dateBegin);
									
			}
	
	
		}
	
		$shops = $this->_getParam("shops");
		$dateBegin = $this->_getParam("db");
		$token = $this->_getParam("token");
		$val = $this->_getParam("su");
		$dateCheck = date("Y-m-d",$token);
	
		
		$this->view->stList = $stDetail->listStaffByNickName();
		$arrResult = array();
	
		if($dateCheck == $dateBegin){
	
			$shopList = unserialize(base64_decode($shops));
			$dateEnd = Model_DatetimeHelper::adjustDays("add", $dateBegin, 6);
			$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
			
			$this->view->su = isset($val)?$val:"normal";
			$this->view->shops = $shops; //shop encode
			$this->view->dateBegin = $dateBegin;
			$this->view->spList = $shopList; //shop list
			$this->view->arrDate = $arrDate;
			
			
			foreach($shopList as $shopKey => $shopHead){
	
				foreach($arrDate as $dateKey => $dateValue){

					$arrResult[$shopKey][$dateKey] = $tSheet->listArrangedShiftByDateByShopWithFormat($shopHead, $dateValue, $dateValue);
	
				}
			}
				
		}//end of date begin
		if($_POST){
			//d($_POST);
	
			if(isset($_POST["arr_Detail"])){
					
				foreach($shopList as $shopKey => $shopHead){
	
					foreach($arrDate as $dateKey => $dateValue){
							
						//var_dump($shopHead,$dateValue);
						if(isset($_POST["arr_Detail"][$shopKey][$dateKey])){
							$arrResult[$shopKey][$dateKey] = $_POST["arr_Detail"][$shopKey][$dateKey];
						}
						else{
							$arrResult[$shopKey][$dateKey] = "";
						}
					}
	
				}
					
			}//end of arr_detail
	
			if(isset($_POST['recal'])){
				foreach($shopList as $shopKey => $shopHead){
	
					foreach($arrDate as $dateKey => $dateValue){
							
						//var_dump($shopHead,$dateValue);
						if(isset($_POST["arr_Detail"][$shopKey][$dateKey])){
							$array = array();
							foreach ($_POST["arr_Detail"][$shopKey][$dateKey] as $v2){;
							
							$tmpId = $v2[0];
							$tmpStH = $v2[1];
							$tmpStM = $v2[2];
							$tmpEdH = $v2[3];
							$tmpEdM = $v2[4];
							$tmptsId = $v2[5];
							
							$tmpS = Model_DatetimeHelper::tranferToInt($tmpStH.":".$tmpStM);
							$tmpE = Model_DatetimeHelper::tranferToInt($tmpEdH.":".$tmpEdM);
							
					
								if(($tmpE - $tmpS)/3600 >= 9){
									$tmpbreak = 60;
								}else if(($tmpE - $tmpS)/3600 >= 5){
									$tmpbreak = 30;
								}else{
									$tmpbreak = 0;
								}
	
								$tmpTotalH = ($tmpE - $tmpS)/3600 - ($tmpbreak)/60;
								$tmpex = $v2[8];
							
							
								$tmpArr = array($tmpId,$tmpStH,$tmpStM,$tmpEdH,$tmpEdM,$tmptsId,$tmpbreak,$tmpTotalH,$tmpex);
								$array[] = $tmpArr;
							
							}
							$arrResult[$shopKey][$dateKey] = $array;
						}
						else{
							$arrResult[$shopKey][$dateKey] = "";
						}
					}
	
				}
			}
				
			// add button
			if(isset($_POST["btn_addto"])){
					
					
				$arrDailyTmp = array();
					
				for($i=1;$i<=3;$i++){
					$str = "staff_name_".$i;
					if($_POST[$str]!==""){
						$breakTime = 0;
						$totalHours = round(($_POST["shift_end_hour_".$i] - $_POST["shift_start_hour_".$i]) + ($_POST["shift_end_min_".$i] - $_POST["shift_start_min_".$i])/60,2);
	
						if($totalHours >=5){
							$breakTime = 30;
							$totalHours -= 0.5;
						}
						if($totalHours >=9){
							$breakTime = 60;
							$totalHours -= 1;
						}
						$arrDailyTmp[] = array($_POST[$str],$_POST["shift_start_hour_".$i],$_POST["shift_start_min_".$i],$_POST["shift_end_hour_".$i],$_POST["shift_end_min_".$i],"new".date("U").$i,$breakTime,$totalHours,0);
					}
				}
				
				
				$counter = 0;
				foreach($_POST["choice"] as $theShop => $dates ){
	
					foreach($dates as $theDate => $value){
						if(isset($arrDailyTmp[0][0])){
							$arrDailyTmp[0][5] .= $counter;
							$stdId1 = $arrDailyTmp[0][0];
							$counter++;
						}
						if(isset($arrDailyTmp[1][0])){
							$arrDailyTmp[1][5] .= $counter;
							$stdId2 = $arrDailyTmp[1][0];
							$counter++;
						}
						if(isset($arrDailyTmp[2][0])){
							$arrDailyTmp[2][5] .= $counter;
							$stdId3 = $arrDailyTmp[2][0];
							$counter++;
						}
						if($value){
							$leaveDate = $_POST['pickDate'][$theShop][$theDate];
		
							$check1 = false;
							$check2 = false;
							$check3 = false;
							$check4 = false;
							$check5 = false;
							$check6 = false;
							
							
							
							
							if(!empty($stdId1)){
								$leaveCheck1 = $leave->getApproveLeaveByIdDate($stdId1, $leaveDate);
								$stfNi = $stDetail->getDetail($stdId1);
								if(!empty($leaveCheck1)){
									
									$check1 = true;
								}
							}
							if(!empty($stdId2)){
								$leaveCheck2 = $leave->getApproveLeaveByIdDate($stdId2, $leaveDate);
								$stfNi2 = $stDetail->getDetail($stdId2);
								if(!empty($leaveCheck2)){
									
									$check2 = true;
								}
							}
							if(!empty($stdId3)){
								$leaveCheck3 = $leave->getApproveLeaveByIdDate($stdId3, $leaveDate);
								$stfNi3 = $stDetail->getDetail($stdId3);
								if(!empty($leaveCheck3)){
									
									$check3 = true;
								}
							}
							if($leaveDate == $dateEnd && $leaveDate > '2015-09-01'){
								if($stfNi['is_sun'] == 0 && !empty($stfNi)){
									$check4 = true;
								}	
								
								if($stfNi2['is_sun'] == 0 && !empty($stfNi2)){
									$check5 = true;
								}
								
								if($stfNi3['is_sun'] == 0 && !empty($stfNi3)){
									$check6 = true;
								}
							}
							
							
							
							if($check1 == true){
								$errFlag = true;
								$name = ucwords(Model_EncryptHelper::getSslPassword($stfNi["n"]));
								$nickName = $stfNi['ni'];
								$stfLeaveDate = $leaveCheck1['period_start'];
									
								$content = "Staff (".$nickName.") ". $name ." has apply leave on ".$stfLeaveDate;
								echo "<script language='javascript'> alert('$content');</script>";
									
							}
							if($check2 == true){
								$errFlag = true;
								$name2 = ucwords(Model_EncryptHelper::getSslPassword($stfNi2["n"]));
								$nickName2 = $stfNi2['ni'];
								$stfLeaveDate2 = $leaveCheck2['period_start'];
								$content2 = "Staff (".$nickName2.") ". $name2 ." has apply leave on ".$stfLeaveDate2;
								echo "<script language='javascript'> alert('$content2');</script>";
								
							}
								
							if($check3 == true){
								$errFlag = true;
								$name3 = ucwords(Model_EncryptHelper::getSslPassword($stfNi3["n"]));
								$nickName3 = $stfNi3['ni'];
								$stfLeaveDate3 = $leaveCheck3['period_start'];
								$content3 = "Staff (".$nickName3.") ". $name3 ." has apply leave on ".$stfLeaveDate3;
								echo "<script language='javascript'> alert('$content3');</script>";
									
							}
							
							if($check4 == true){
								$errFlag = true;
								$name = ucwords(Model_EncryptHelper::getSslPassword($stfNi["n"]));
								$nickName = $stfNi['ni'];	
								$content = "Staff (".$nickName.") ". $name ." cannot work on Sunday(".$dateEnd.")";
								echo "<script language='javascript'> alert('$content');</script>";
									
							}
							if($check5 == true){
								$errFlag = true;
								$name2 = ucwords(Model_EncryptHelper::getSslPassword($stfNi2["n"]));
								$nickName2 = $stfNi2['ni'];
								$content2 = "Staff (".$nickName2.") ". $name2 ." cannot work on Sunday(".$dateEnd.")";
								echo "<script language='javascript'> alert('$content2');</script>";
							
							}
							
							if($check6 == true){
								$errFlag = true;
								$name3 = ucwords(Model_EncryptHelper::getSslPassword($stfNi3["n"]));
								$nickName3 = $stfNi3['ni'];
								$content3 = "Staff (".$nickName3.") ". $name3 ." cannot work on Sunday(".$dateEnd.")";
								echo "<script language='javascript'> alert('$content3');</script>";
								
							}
							
							
							
								
							if(empty($arrResult[$theShop][$theDate])){
								$arrDailyTmpRes2= array();
									foreach($arrDailyTmp as $key => $tmp){
										$staffID = $tmp[0];
										if(!empty($stdId1)){ //check staff1 annual leave
											if($staffID == $stdId1){
												if(!$check1 && !$check4){
													$arrDailyTmpRes2[] = $tmp;
												}
											}
										}
										
										if(!empty($stdId2)){ //check staff2 annual leave
											if($staffID == $stdId2){
												if(!$check2 && !$check5){
													$arrDailyTmpRes2[] = $tmp;
												}
											}
										}
										
										if(!empty($stdId3)){ //check staff3 annual leave
											if($staffID == $stdId3){
												if(!$check3 && !$check6){
													$arrDailyTmpRes3[] = $tmp;
												}
											}
										}
									}
	
									$arrResult[$theShop][$theDate] = $arrDailyTmpRes2;
							}else{
									$arrDailyTmpRes = array();
									foreach($arrDailyTmp as $key => $tmp){
	
										$staffID = $tmp[0];
										$startHour = $tmp[1];
										$startmin = $tmp[2];
	
										$errFlag = false;
	
										foreach($arrResult[$theShop][$theDate] as $resKey => $v){
											if($v[0] == $staffID && ( ($v[3]*100 +$v[4]) > ($startHour*100 + $startmin) )){
												$errFlag = true;
												echo "<script language='javascript'> alert('Duplicated Enty Entered! Will not Accept');</script>";
											
											}
										}
												
											if(!empty($stdId1)){ //check staff1 annual leave
												if($staffID == $stdId1){
													if(!$errFlag && !$check1){
														$arrDailyTmpRes[] = $tmp;
													}
												}
											}
											
											if(!empty($stdId2)){ //check staff2 annual leave
												if($staffID == $stdId2){
													if(!$errFlag && !$check2){
														$arrDailyTmpRes[] = $tmp;
													}
												}
											}
											
											if(!empty($stdId3)){ //check staff3 annual leave
												if($staffID == $stdId3){
													if(!$errFlag && !$check2){
														$arrDailyTmpRes[] = $tmp;
													}
												}
											}
									}
	
								$arrResult[$theShop][$theDate] = array_merge($arrResult[$theShop][$theDate],$arrDailyTmpRes);
	
							}//End of else
												
						}//End of If value
												
					}//End of each date
	
				}//End of Foreach date choice
												
			}//End of add
	
		}// End of post
	
		$this->view->arrResultLive = $arrResult;
		//d($arrResult);
	}
	
	
	
	/**
	 * this is the landing page of online roster , 
	 * this page change according the current time 
	 * to roster arrange page and roster confirm page 
	 */
	
	
	/**
	 * this is the one in the company info page to show the roster to the shop staff
	 */
	public function onlineRosterLastWeekAction(){
		$shop = base64_decode($this->_getParam("shop"));
		
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		
		$this->view->shops = $shop;
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
		$tSheet = new Model_DbTable_Roster_Timesheet();
		
		$arrResult = array();
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		$this->view->arrDate = $arrDate;
		foreach($arrDate as $dateKey => $dateValue){
		
			//var_dump($shopHead,$dateValue);
			$arrResult[0][$dateKey] = $tSheet->listShiftByDateByShopWithFormat($shop, $dateValue, $dateValue);
		
		}
		$this->view->arrResultLive = $arrResult;
		
	}
	/**
	 * this is the one in the company info page to show the staff current week roster 
	 */
	public function onlineRosterThisWeekAction(){

		$shop = base64_decode($this->_getParam("shop"));
		
		$dateBegin = Model_DatetimeHelper::getThisWeekMonday();
		$dateEnd = Model_DatetimeHelper::getThisWeekSunday();

		$this->view->shops = $shop;
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
		$tSheet = new Model_DbTable_Roster_Timesheet();
		
		$arrResult = array();
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		$this->view->arrDate = $arrDate;
		foreach($arrDate as $dateKey => $dateValue){
		
			//var_dump($shopHead,$dateValue);
			$arrResult[0][$dateKey] = $tSheet->listShiftByDateByShopWithFormat($shop, $dateValue, $dateValue);
		
		}
		$this->view->arrResultLive = $arrResult;		
		
	}
	
	/**
	 * this is the landing page to show the link of check last current next week roster 
	 */
	public function checkOnlineRosterAction(){
		
		$this->view->shop = $this->_getParam("shop");
	}
	
	/**
	 * this is the one in the company info page to show the staff next week roster
	 */
	public function onlineRosterNextWeekAction(){
		$shop = base64_decode($this->_getParam("shop"));
		
		$dateBegin = Model_DatetimeHelper::adjustDays("add",Model_DatetimeHelper::getThisWeekMonday(),7);
		$dateEnd = Model_DatetimeHelper::adjustDays("add",Model_DatetimeHelper::getThisWeekSunday(),7);
		
		$this->view->shops = $shop;
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
		$tSheet = new Model_DbTable_Roster_Timesheet();
		
		$arrResult = array();
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		$this->view->arrDate = $arrDate;
		foreach($arrDate as $dateKey => $dateValue){
		
			//var_dump($shopHead,$dateValue);
			$arrResult[0][$dateKey] = $tSheet->listShiftByDateByShopWithFormat($shop, $dateValue, $dateValue);
		
		}
		$this->view->arrResultLive = $arrResult;		
		
		
	}
	/**
	 * this is the page for manager to confirm current and last week roster 
	 */
	public function onlineRosterConfirmAction(){
		
		
		$shops = $this->_getParam("shops");
		$dateBegin = $this->_getParam("db");
		$token = $this->_getParam("token");
		
		$val = $this->_getParam("su");
		$this->view->su = isset($val)?$val:"normal";
		$this->view->trigger = "";
		
		
		
		$this->view->shops = $shops;
		$this->view->dateBegin = $dateBegin;
		
		
		date_default_timezone_set('Australia/Melbourne');
		$dateCheck = date("Y-m-d",$token);
		
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$this->view->stList = $stDetail->listStaffByNickName();
		$arrResult = array();
				
		
		if($dateCheck == $dateBegin){
				
			$shopList = unserialize(base64_decode($shops));
			$this->view->spList = $shopList;
			$dateEnd = Model_DatetimeHelper::adjustDays("add", $dateBegin, 6);
			$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
			$this->view->arrDate = $arrDate;
			foreach($shopList as $shopKey => $shopHead){

				foreach($arrDate as $dateKey => $dateValue){
				
					//var_dump($shopHead,$dateValue);
					$arrResult[$shopKey][$dateKey] = $tSheet->listShiftByDateByShopWithFormat($shopHead, $dateValue, $dateValue); 					
					//var_dump($arrResult[$shopKey][$dateKey]);
				}	
								
			}		
				
		}//end of dateBegin		
		//var_dump($arrResult);
		//d($arrResult);
		if($_POST){
						
			//$arrResult = isset($_POST["arr_Detail"])?$_POST["arr_Detail"]:$arrResult;
			//d($_POST);
			if($_POST['trigger']!=""){
				
				$this->view->trigger = $_POST['trigger'];
			}

			if(isset($_POST["arr_Detail"])){
				
				foreach($shopList as $shopKey => $shopHead){
				
					foreach($arrDate as $dateKey => $dateValue){
				
						//var_dump($shopHead,$dateValue);
						if(isset($_POST["arr_Detail"][$shopKey][$dateKey])){
							$arrResult[$shopKey][$dateKey] = $_POST["arr_Detail"][$shopKey][$dateKey];
						}
						else{
							$arrResult[$shopKey][$dateKey] = "";
						}	
					}
				
				}				

				//$arrResult = array_merge($arrResult,$_POST["arr_Detail"]);
						
			}
			
			//var_dump($_POST["arr_Detail"],$arrResult);
			

			if(isset($_POST["btn_addto"])){

				//$arrResult = isset($_POST["arr_Detail"])?$_POST["arr_Detail"]:$arrResult;
			
				$arrDailyTmp = array();
				
						$i = 1;
						$totalHours = round(($_POST["shift_end_hour_".$i] - $_POST["shift_start_hour_".$i]) + ($_POST["shift_end_min_".$i] - $_POST["shift_start_min_".$i] - $_POST["break_time"])/60,2);
						$arrDailyTmp[] = array($_POST["staff_name_".$i],$_POST["shift_start_hour_".$i],$_POST["shift_start_min_".$i],$_POST["shift_end_hour_".$i],$_POST["shift_end_min_".$i],"new".date("U"),$_POST["break_time"],$totalHours,0,"#8080FF");	
			
				$counter = 0;		
				foreach($_POST["choice"] as $theShop => $dates ){
								
							foreach($dates as $theDate => $value){
								$arrDailyTmp[0][5] .= $counter;
								$counter++; 
								if($value){
						
									if($arrResult[$theShop][$theDate]==""){
										
										$arrResult[$theShop][$theDate] = $arrDailyTmp;
									}
									else{
											
										$arrResult[$theShop][$theDate] = array_merge($arrResult[$theShop][$theDate],$arrDailyTmp);
											
									}
								}
						
							}
								
						}

			}
				
				

		}

		$this->view->arrResultLive = $arrResult; 
		//$this->view->arrResult = base64_encode(serialize($arrResult));	
		//echo "+++++++++++++++++++++++++++++++++++++++++++";
		//echo "<pre>";
		//var_dump( get_defined_vars() );
		//echo "</pre>";
		
		$this->renderScript("/roster/online-roster-confirm-140528.phtml");
	} 
	
	
	/**
	 * New confirm roster
	 */
	public function onlineRosterConfirm2015Action(){
	
	
		$shops = $this->_getParam("shops");
		$dateBegin = $this->_getParam("db");
		$token = $this->_getParam("token");
	
		$val = $this->_getParam("su");
		$this->view->su = isset($val)?$val:"normal";
		$this->view->trigger = "";

		
	
	
		date_default_timezone_set('Australia/Melbourne');
		$dateCheck = date("Y-m-d",$token);
	
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		
		
		$arrResult = array();
	
	
		if($dateCheck == $dateBegin){
	
			$shopList = unserialize(base64_decode($shops));
			
			$this->view->stList = $stDetail->listStaffByNickName();
			$this->view->dateBegin = $dateBegin;
			$this->view->shops = $shops; //shop discode
			$this->view->spList = $shopList; //shop list
			
			$dateEnd = Model_DatetimeHelper::adjustDays("add", $dateBegin, 6);
			$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
			$this->view->arrDate = $arrDate;
			foreach($shopList as $shopKey => $shopHead){
	
				foreach($arrDate as $dateKey => $dateValue){

					$arrResult[$shopKey][$dateKey] = $tSheet->listShiftByDateByShopWithFormat($shopHead, $dateValue, $dateValue);

				}
	
			}
	
		}
		
		if($_POST){

	
			if(isset($_POST["arr_Detail"])){
	
				foreach($shopList as $shopKey => $shopHead){
	
					foreach($arrDate as $dateKey => $dateValue){
	
						if(isset($_POST["arr_Detail"][$shopKey][$dateKey])){
							$arrResult[$shopKey][$dateKey] = $_POST["arr_Detail"][$shopKey][$dateKey];
						}
						else{
							$arrResult[$shopKey][$dateKey] = "";
						}
					}
	
				}

			}
			
			if(isset($_POST['recal'])){
				foreach($shopList as $shopKey => $shopHead){
			
					foreach($arrDate as $dateKey => $dateValue){
							
						//var_dump($shopHead,$dateValue);
						if(isset($_POST["arr_Detail"][$shopKey][$dateKey])){
							
							$array = array();
							foreach ($_POST["arr_Detail"][$shopKey][$dateKey] as $v2){
									
								$tmpId = $v2[0];
								$tmpStH = $v2[1];
								$tmpStM = $v2[2];
								$tmpEdH = $v2[3];
								$tmpEdM = $v2[4];
								$tmptsId = $v2[5];
									
								$tmpS = Model_DatetimeHelper::tranferToInt($tmpStH.":".$tmpStM);
								$tmpE = Model_DatetimeHelper::tranferToInt($tmpEdH.":".$tmpEdM);

								if(($tmpE - $tmpS)/3600 >= 9){
									$tmpbreak = 60;
								}else if(($tmpE - $tmpS)/3600 >= 5){
									$tmpbreak = 30;
								}else{
									$tmpbreak = 0;
								}
			
									$tmpTotalH = ($tmpE - $tmpS)/3600 - ($tmpbreak)/60;
									$tmpex = $v2[8];
									$tmpcolor = $v2[9];
									$tmpApp = $v2[10];
									$tmpLock = $v2[11];	
										
									$tmpArr = array($tmpId,$tmpStH,$tmpStM,$tmpEdH,$tmpEdM,$tmptsId,$tmpbreak,$tmpTotalH,$tmpex,$tmpcolor,$tmpApp,$tmpLock);
									$array[] = $tmpArr;
								
							}
							$arrResult[$shopKey][$dateKey] = $array;
						}
						else{
							$arrResult[$shopKey][$dateKey] = "";
						}
					}
			
				}
			}
			
			


			if(isset($_POST["btn_addto"])){

				$arrDailyTmp = array();
	
				$i = 1;
				$totalHours = round(($_POST["shift_end_hour_".$i] - $_POST["shift_start_hour_".$i]) + ($_POST["shift_end_min_".$i] - $_POST["shift_start_min_".$i] - $_POST["break_time"])/60,2);
				$arrDailyTmp[] = array($_POST["staff_name_".$i],$_POST["shift_start_hour_".$i],$_POST["shift_start_min_".$i],$_POST["shift_end_hour_".$i],$_POST["shift_end_min_".$i],"new".date("U"),$_POST["break_time"],$totalHours,0,"#8080FF",-1);
					
				$counter = 0;
				foreach($_POST["choice"] as $theShop => $dates ){
	
					foreach($dates as $theDate => $value){
						$arrDailyTmp[0][5] .= $counter;
						$counter++;
						if($value){
				
							if($arrResult[$theShop][$theDate]==""){
	
								$arrResult[$theShop][$theDate] = $arrDailyTmp;
							}
							else{
									
								$arrResult[$theShop][$theDate] = array_merge($arrResult[$theShop][$theDate],$arrDailyTmp);
									
							}
	
							
						}
	
					}
	
				}
	
			}
	
	
	
		}
	
		$this->view->arrResultLive = $arrResult;
		//d($arrResult);
	}
	
	
	/**
	* @author Leo
	* @version 2014-06-25
	* Reason input null validation 
	**/
	public function saveConfirmRosterAction(){
		
		//echo "<pre>";//
		//var_dump($_POST);//
		//echo "</pre>";//
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$arrResult = $_POST["arr_Detail"];
		$arrShops = unserialize(base64_decode($_POST["shops"]));
		//var_dump($arrShops);//
		$dateBegin = $_POST["date_begin"];
		$dateEnd = Model_DatetimeHelper::adjustDays("add", $dateBegin, 6);
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		$ts = new Model_DbTable_Roster_Timesheet();
		$lock = null;
		if(isset($_POST['btn_confirm_notify'])){
			
			$lock = 1;
		}
		
		
		$appr = -1;
		$needAppr = false;
		if(isset($_POST['su_final_arrange_app'])) {
			$appr = 1;
			$needAppr = true;
		}
		if(isset($_POST['su_final_arrange_rej'])) {
			$appr = -2;
			$needAppr = true;
		}
		
		
		$result = 0;
		
		$overBudget = isset($_POST['reason']);
		//140613
		
		$reason = $_POST['reason'];
		$str = implode('|', $reason);
		$test = trim($str);

		if(strlen($test) <= 80){
					$result++;
		}
			
		$button = $_POST['btn_final'];
		if($result!=0 && $button == 'EXCEED BUDGET, SAVE ARRANGE AND WAITING FOR APPROVAL'){
			$this->view->errorFlag2 = true;
		
			$this->view->errorMessage = "You did not fill the reason, please fill and resubmit";
		
		}else{
		foreach($arrShops as $shopKey => $shopValue){
			foreach($arrDate as $dateKey => $dateValue){
				echo $cot = count($arrResult[$shopKey][$dateKey]);//
				for($i=0;$i<$cot;$i++){
					if(is_numeric($arrResult[$shopKey][$dateKey][$i][5])){
						//echo "exist";//
						$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
						$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
						$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
						
						$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
						$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);
						
						if($dateValue > $dateToday){
							if($needAppr || $overBudget ){
								$ts->managerConfirmArrangeTimesheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$appr);								
								
							}
							else{
								$ts->managerConfirmArrangeTimesheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime);								
							}
						}
						else{
							if($needAppr || $overBudget ){
								$ts->managerConfirmTimeSheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$lock,$appr);								
							}
							else{
								$ts->managerConfirmTimeSheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$lock);
							}							

						}
						
						//echo $shopValue;
					}
					if(substr($arrResult[$shopKey][$dateKey][$i][5],0,3)=="new"){
						//echo "new";//
						
						$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
						$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
						$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
						
						$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
						$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);
						
						if($dateValue > $dateToday){
							$ts->managerArrangeTimesheet($arrResult[$shopKey][$dateKey][$i][0], $shopValue, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime);
						}
						else{
							$ts->managerAddTimesheet($arrResult[$shopKey][$dateKey][$i][0], $shopValue, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$lock);
						}
						
						
						
						//echo $dateValue;
						//echo $shopValue;
					}
				}
				
			}	
		}
		
		
		if(($overBudget || $needAppr) && !$lock){
				
			//$arrShops = unserialize(base64_decode($_POST['shops']));
			//d($_POST);
			$obLog = new Model_Hr_Overbudgetlog();
			$subject = "Over Budge Request Approval";
				
			$mailBody = "";
				
			$mail = new Model_Emailshandler();
			$shopHead = new Model_DbTable_Shoplocation();
				
			foreach ($_POST['reason'] as $key => $v){
				$btHour = $_POST['week_budget_hour'][$key];
				$toHour = $_POST['week_total_hour'][$key];
				
				
				$trHour = $_POST['week_total_tr_hour'][$key];
				$trBtHour = $_POST['week_budget_tr_hour'][$key];
				
				$ext = $toHour - $btHour;
				$trExt = $trHour - $trBtHour;
				
				
				$reasons = str_replace("|","<br />",$v);
		
				$mailBody = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} , Exceed Hours {$ext}, Trainee Budget is {$trBtHour} and Allocated Hour is {$trHour} ,Exceed Hour is {$trExt} For the Following Reason [{$reasons}] , On Week Begin {$dateBegin},Please Go to Page to Approval It.";
				if($ext <= 0){
					
					$mailBody = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} ,Trainee Hour Has Exceed the Budget, Trainee Budget is {$trBtHour} and Allocated Hour is {$trHour} ,Exceed Hour is {$trExt}  For the Following Reason [{$reasons}] , On Week Begin {$dateBegin},Please Go to Page to Approval It.";
					
				}
				
				$mailBodyApp = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} , Exceed Hours {$ext},On Week Begin {$dateBegin},Has Been Approved";
				$mailBodyRej = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} , Exceed Hours {$ext} , On Week Begin {$dateBegin},Has Been Rejected, You must Fix It";
		
				if($appr == -1){
					$mail->sendActionEmail("simon.seop@phonecollection.com.au", $subject, $mailBody);
					//$mail->sendNormalEmail("office@phonecollection.com.au;simon.seop@phonecollection.com.au", $subject, $mailBody);
					echo "Email Sent To HQ, Log Saved";
					$obLog->initOverbudgetlog($arrShops[$key], $dateBegin, $dateEnd, $reasons,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(), $appr,$ext,$trExt);
					
				}
		
				$shopEmail = $shopHead->getShopMailByHead($arrShops[$key]);
				$shopManager = $shopHead->getStoreManMailByHead($arrShops[$key]);
				$areaManager = $shopHead->getAreaManMailByHead($arrShops[$key]);
		
				if($appr == 1){
					
					$idObLine = $obLog->getByShop($arrShops[$key], $dateBegin, $dateEnd);
					$obLog->updateStatus($idObLine['id_overbudget'], $appr,4,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow());
						
						
					$mail->sendNormalEmail($shopEmail,"Your Over Budget Request Has Been Approved", $mailBodyApp);
					$mail->sendNormalEmail($shopManager,"Your Over Budget Request Has Been Approved", $mailBodyApp);
					$mail->sendNormalEmail($areaManager,"Your Over Budget Request Has Been Approved", $mailBodyApp);
					echo "Email Sent To Shop".$shopEmail;
				}
		
				if($appr == -2){
					
					$idObLine = $obLog->getByShop($arrShops[$key], $dateBegin, $dateEnd);
					$obLog->updateStatus($idObLine['id_overbudget'], $appr,4,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow());
						
						
					$mail->sendActionEmail($shopEmail,"Your Over Budget Request Has Been Rejected", $mailBodyRej);
					$mail->sendActionEmail($shopManager,"Your Over Budget Request Has Been Rejected", $mailBodyRej);
					$mail->sendActionEmail($areaManager,"Your Over Budget Request Has Been Rejected", $mailBodyRej);
					echo "Email Sent To Shop".$shopEmail;
				}
		
			}
				
		
		}
		
		}
		
		
	}
	
	/**
	 * @author Leo
	 * @version 2014-06-25
	 * Reason input null validation
	 **/
	public function saveConfirmRoster2015Action(){
		$obLog = new Model_Hr_Overbudgetlog();
		$dateToday = Model_DatetimeHelper::dateToday();
	
		$arrResult = $_POST["arr_Detail"];
		$arrShops = unserialize(base64_decode($_POST["shops"]));

		$dateBegin = $_POST["date_begin"];
		$dateEnd = Model_DatetimeHelper::adjustDays("add", $dateBegin, 6);
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		$ts = new Model_DbTable_Roster_Timesheet();
		$shopHead = new Model_DbTable_Shoplocation();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		$mail = new Model_Emailshandler();

		$appr = -1;

		$overBudget = isset($_POST['reason']);
		$staffRemind = array();
			
		if(isset($_POST['btn_final'])){
			$appr = 2;
			//dd($arrResult);
			foreach($arrShops as $shopKey => $shopValue){
				foreach($arrDate as $dateKey => $dateValue){
					echo $cot = count($arrResult[$shopKey][$dateKey]);//
					for($i=0;$i<$cot;$i++){
						if(is_numeric($arrResult[$shopKey][$dateKey][$i][5])){
							
							$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
							$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
							$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
			
							$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
							$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);

							$ts->managerConfirmTimeSheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,1,$appr);
						}
						
						if(substr($arrResult[$shopKey][$dateKey][$i][5],0,3)=="new"){
							
							$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
							$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
							$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
			
							$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
							$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);

							$insertId = $ts->managerArrangeTimesheet($arrResult[$shopKey][$dateKey][$i][0], $shopValue, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$appr);
							$ts->managerConfirmTimeSheet($insertId, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,1,$appr);
						}
						
						if($dateValue == $dateEnd){
							$staffPermit = $stfDetail->getDetail($arrResult[$shopKey][$dateKey][$i][0]);
							if($staffPermit['is_sun'] == 0){
								$staffRemind[$shopValue][$staffPermit['ni']."(".ucwords(Model_EncryptHelper::getSslPassword($staffPermit['n'])).")"]['name'] = $staffPermit['ni']."(".ucwords(Model_EncryptHelper::getSslPassword($staffPermit['n'])).")";
								$staffRemind[$shopValue][$staffPermit['ni']."(".ucwords(Model_EncryptHelper::getSslPassword($staffPermit['n'])).")"]['Time'] = $strDateBegin." - ".$strDateEnd;
							}
						}
					}
			
				}
				
				if($overBudget){
					
					
					$subject = "Over Budge Request Approval";
					
					$mailBody = "";
					
					
					
					
					foreach ($_POST['reason'] as $key => $v){
					
						$btHour = $_POST['week_budget_hour'][$key];
						$toHour = $_POST['week_total_hour'][$key];
					
					
						$trHour = $_POST['week_total_tr_hour'][$key];
						$trBtHour = $_POST['week_budget_tr_hour'][$key];
					
						$ext = $toHour - $btHour;
						$trExt = $trHour - $trBtHour;
					
					
						$reasons = str_replace("|","<br />",$v);
					
						$mailBody = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} , Exceed Hours {$ext}, Trainee Budget is {$trBtHour} and Allocated Hour is {$trHour} ,Exceed Hour is {$trExt} For the Following Reason [{$reasons}] , On Week Begin {$dateBegin},Please Go to Page to Approval It.";
						if($ext <= 0){
								
							$mailBody = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} ,Trainee Hour Has Exceed the Budget, Trainee Budget is {$trBtHour} and Allocated Hour is {$trHour} ,Exceed Hour is {$trExt}  For the Following Reason [{$reasons}] , On Week Begin {$dateBegin},Please Go to Page to Approval It.";
								
						}
					
						$mail->sendActionEmail("simon.seop@phonecollection.com.au", $subject, $mailBody);
						echo "Email Sent To HQ, Log Saved";
						$obLog->initOverbudgetlog($arrShops[$key], $dateBegin, $dateEnd, $reasons,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(), -1,$ext,$trExt);
		
					}

				} //Sent Over budget reason
				

				
			}
			
			if(!empty($staffRemind)){
				$mailDetail = "";
				foreach ($staffRemind as $shop => $info){
					$mailDetail .= "SHOP ".$shop." No Permit Sunday Staff<br/>";
					foreach($info as $name => $value){
						$mailDetail .= $name." TIME:".$value['time']."<br/>";
					}
				}
			
				$mail->sendActionEmail('Office@phonecollection.com.au;simon.seop@phonecollection.com.au', 'Sunday no permit staff list', $mailDetail);	
			}
			
			
		}

	
	
			if(isset($_POST['su_final_arrange_app']) || isset($_POST['su_final_arrange_rej'])){
	
			
				foreach ($_POST['reason'] as $key => $v){
					
					$mailBodyApp = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} , Exceed Hours {$ext},On Week Begin {$dateBegin},Has Been Approved";
					$mailBodyRej = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} , Exceed Hours {$ext} , On Week Begin {$dateBegin},Has Been Rejected, You must Fix It";

					$shopEmail = $shopHead->getShopMailByHead($arrShops[$key]);
					$shopManager = $shopHead->getStoreManMailByHead($arrShops[$key]);
					$areaManager = $shopHead->getAreaManMailByHead($arrShops[$key]);
	
					if(isset($_POST['su_final_arrange_app'])){
						$appr = 1;	
						$idObLine = $obLog->getByShop($arrShops[$key], $dateBegin, $dateEnd);
						
						$obLog->updateStatus($idObLine['id_overbudget'], $appr,4,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow());
	
						  $mail->sendNormalEmail($shopEmail,"Your Over Budget Request Has Been Approved", $mailBodyApp);
						  $mail->sendNormalEmail($shopManager,"Your Over Budget Request Has Been Approved", $mailBodyApp);
						  $mail->sendNormalEmail($areaManager,"Your Over Budget Request Has Been Approved", $mailBodyApp);
						echo "Email Sent To Shop".$shopEmail;
						
						foreach($arrShops as $shopKey => $shopValue){
							foreach($arrDate as $dateKey => $dateValue){
								echo $cot = count($arrResult[$shopKey][$dateKey]);//
								for($i=0;$i<$cot;$i++){
									if(is_numeric($arrResult[$shopKey][$dateKey][$i][5])){
											
										$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
										$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
										$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
											
										$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
										$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);
						
										$ts->managerConfirmTimeSheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,1,$appr);
									}
						
									if(substr($arrResult[$shopKey][$dateKey][$i][5],0,3)=="new"){
											
										$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
										$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
										$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
											
										$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
										$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);
						
										$insertId = $ts->managerArrangeTimesheet($arrResult[$shopKey][$dateKey][$i][0], $shopValue, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$appr);
										$ts->managerConfirmTimeSheet($insertId, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,1,$appr);
									}
								}
									
							}
						}
						
						
					}
	
					if(isset($_POST['su_final_arrange_rej'])){

						$appr = -1;
						$idObLine = $obLog->getByShop($arrShops[$key], $dateBegin, $dateEnd);
						$obLog->updateStatus($idObLine['id_overbudget'], $appr,4,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow());
	
	
						$mail->sendActionEmail($shopEmail,"Your Over Budget Request Has Been Rejected", $mailBodyRej);
						$mail->sendActionEmail($shopManager,"Your Over Budget Request Has Been Rejected", $mailBodyRej);
						$mail->sendActionEmail($areaManager,"Your Over Budget Request Has Been Rejected", $mailBodyRej);
						echo "Email Sent To Shop".$shopEmail;
						
						foreach($arrShops as $shopKey => $shopValue){
							foreach($arrDate as $dateKey => $dateValue){
								echo $cot = count($arrResult[$shopKey][$dateKey]);//
								for($i=0;$i<$cot;$i++){
									if(is_numeric($arrResult[$shopKey][$dateKey][$i][5])){
											
										$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
										$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
										$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
											
										$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
										$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);
						
										$ts->managerConfirmTimeSheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,1,$appr);
									}
						
									if(substr($arrResult[$shopKey][$dateKey][$i][5],0,3)=="new"){
											
										$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
										$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
										$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
											
										$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
										$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);
						
										$insertId = $ts->managerArrangeTimesheet($arrResult[$shopKey][$dateKey][$i][0], $shopValue, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$appr);
										$ts->managerConfirmTimeSheet($insertId, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,1,$appr);
									}
								}
									
							}
						}
					}
	
				}
		
			}

	}
	
	
	/**
	 * ON 140627 This is as Manager's Request to Arrange Multi Weeks Roster
	 * if need approval, send separate weeks' approval request to carla 
	 * @todo Need to modify the final interface make it look better then the orignal one 
	 * with debug info
	 * @author Norman
	 * 
	 */
	public function saveArrangeRosterMultiWeekAction(){
		
		$arrResult = $_POST["arr_Detail"];
		$arrShops = unserialize(base64_decode($_POST["shops"]));
		$dateBegin = $_POST["date_begin"];
		$dateEnd = $_POST["date_end"];

		$ts = new Model_DbTable_Roster_Timesheet();
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		
		
		$appr = -1;
		$overBudget = isset($_POST['reason']);
		
		foreach($arrShops as $shopKey => $shopValue){
			foreach($arrDate as $dateKey => $dateValue){
				if(isset($arrResult[$shopKey][$dateKey])){
					$cot = count($arrResult[$shopKey][$dateKey]); // how many lines I need to update 
						for($i=0;$i<$cot;$i++){
							
							if(is_numeric($arrResult[$shopKey][$dateKey][$i][5])){
								
								$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
								$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
								$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
							
								$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
								$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);
								
								$weekKey = floor($dateKey/7);
								if(isset($_POST['reason'][$weekKey])){
									$ts->managerConfirmArrangeTimeSheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$appr);
									
									$stLine = $stDetail->getDetail($arrResult[$shopKey][$dateKey][$i][5]);
									if($stLine['a'] == 9){
									
										$stDetail->reActiveStaff($stLine['id']);
										$stInfo->activeStaff($stLine['id']);
									}
								
								}
								else{
							
									$ts->managerConfirmArrangeTimeSheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime);
								
									$stLine = $stDetail->getDetail($arrResult[$shopKey][$dateKey][$i][5]);
									if($stLine['a'] == 9){
									
										$stDetail->reActiveStaff($stLine['id']);
										$stInfo->activeStaff($stLine['id']);
									}
								}

							}
							if(substr($arrResult[$shopKey][$dateKey][$i][5],0,3)=="new"){
							
								$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
								$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
								$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
							
								$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
								$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);
								$weekKey = floor($dateKey/7);
								if(isset($_POST['reason'][$weekKey])){
									$ts->managerArrangeTimesheet($arrResult[$shopKey][$dateKey][$i][0], $shopValue, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$appr);
									
									$stLine = $stDetail->getDetail($arrResult[$shopKey][$dateKey][$i][0]);
									if($stLine['a'] == 9){
									
										$stDetail->reActiveStaff($stLine['id']);
										$stInfo->activeStaff($stLine['id']);
									}
									
								}
								else{
									$ts->managerArrangeTimesheet($arrResult[$shopKey][$dateKey][$i][0], $shopValue, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime);
									
									$stLine = $stDetail->getDetail($arrResult[$shopKey][$dateKey][$i][0]);
									if($stLine['a'] == 9){
									
										$stDetail->reActiveStaff($stLine['id']);
										$stInfo->activeStaff($stLine['id']);
									}
								
								}
							
							}	
							
						}	
				}
			}
		}
		
		//over budget
		if($overBudget){
				
			//$arrShops = unserialize(base64_decode($_POST['shops']));
			//d($_POST);
			$obLog = new Model_Hr_Overbudgetlog();
			$subject = "Over Budge Request Approval";
				
			$mailBody = "";
				
			$mail = new Model_Emailshandler();
			$shopHead = new Model_DbTable_Shoplocation();
				
			foreach ($_POST['reason'] as $key => $v){
				
				$btHour = $_POST['week_budget_hour'][$key];
				$toHour = $_POST['week_total_hour'][$key];
				$ext = $toHour - $btHour;
				
				$trHour = $_POST['week_total_tr_hour'][$key];
				$trBtHour = $_POST['week_budget_tr_hour'][$key];
				
				$trExt = $trHour - $trBtHour;
				
				$reasons = str_replace("|","<br />",$v);
				
				$dateBeginWeek = Model_DatetimeHelper::adjustDays("add", $dateBegin, $key*7);
				$dateEndWeek = Model_DatetimeHelper::adjustDays("add", $dateBeginWeek,6);
				
				$mailBody = "SHOP {$arrShops[0]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} , Exceed Hours {$ext}, Trainee Budget is {$trBtHour} and Allocated is {$trHour}, Excced Hour is {$trExt} For the Following Reason [{$reasons}] , On Week Begin {$dateBeginWeek},Please Go to Page to Approval It.";
		
				if($appr == -1){
					$mail->sendActionEmail("simon.seop@phonecollection.com.au", $subject, $mailBody);
					//$mail->sendNormalEmail("office@phonecollection.com.au;simon.seop@phonecollection.com.au", $subject, $mailBody);
					echo "Email Sent To HQ, Log Saved";
					$obLog->initOverbudgetlog($arrShops[0], $dateBeginWeek, $dateEndWeek, $v,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(), $appr,$ext,$trExt);
					
				}
		
				$shopEmail = $shopHead->getShopMailByHead($arrShops[$key]);		
			}
				
		
		}
		
		
		
		
		
	}
	/**
	 * @author Leo
	 * @version 2014-06-30
	 * Reason not null validation
	 */
	public function saveArrangeRosterAction(){
		
		
		//d($_POST);

		$arrResult = $_POST["arr_Detail"];
		$arrShops = unserialize(base64_decode($_POST["shops"]));
		
		$dateBegin = $_POST["date_begin"];
		$dateEnd = Model_DatetimeHelper::adjustDays("add", $dateBegin, 6);
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		$ts = new Model_DbTable_Roster_Timesheet();
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		
		
		
		$appr = -1;
		if(isset($_POST['su_final_arrange_app'])) {$appr = 1; }
		if(isset($_POST['su_final_arrange_rej'])) {
			$appr = -2;
		}	
		
		$result = 0;
		$overBudget = isset($_POST['reason']);
		//140630
		$reason = $_POST['reason'];
		$str = implode('|', $reason);
		$test = trim($str);

		if(strlen($test) <= 80){
			$result++;
		}
			
		$button = $_POST['btn_final_arrange'];
		if($result!=0 && $button == 'EXCEED BUDGET, SAVE ARRANGE AND WAITING FOR APPROVAL'){
			$this->view->errorFlag2 = true;
		
			$this->view->errorMessage = "You did not fill the reason, please fill and resubmit";
		
		}else{
		
		foreach($arrShops as $shopKey => $shopValue){
			foreach($arrDate as $dateKey => $dateValue){
				if(isset($arrResult[$shopKey][$dateKey])){
				echo $cot = count($arrResult[$shopKey][$dateKey]);//
				
				for($i=0;$i<$cot;$i++){
				if(is_numeric($arrResult[$shopKey][$dateKey][$i][5])){
					//echo "exist";//
					$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
					$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
					$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
				
					$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
					$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);
					if($overBudget){
						$ts->managerConfirmArrangeTimeSheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$appr);						 
					}
					else{
						
						$ts->managerConfirmArrangeTimeSheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime);						
					}
					
					// check staff leave status , if is leave , change to not leave , empty leave date 
					$stLine = $stDetail->getDetail($arrResult[$shopKey][$dateKey][$i][5]);
					if($stLine['a'] == 9){
						
						$stDetail->reActiveStaff($stLine['id']);
						$stInfo->activeStaff($stLine['id']);
					}
					
					
					//echo $shopValue;
				}
				if(substr($arrResult[$shopKey][$dateKey][$i][5],0,3)=="new"){
					//echo "new";//
				
					$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
					$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
					$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
				
					$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
					$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);
				
					
					if($overBudget){
						$ts->managerArrangeTimesheet($arrResult[$shopKey][$dateKey][$i][0], $shopValue, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$appr);							
						
						$stLine = $stDetail->getDetail($arrResult[$shopKey][$dateKey][$i][0]);
						if($stLine['a'] == 9){
						
							$stDetail->reActiveStaff($stLine['id']);
							$stInfo->activeStaff($stLine['id']);
						}
					
					}
					else{
						
						$ts->managerArrangeTimesheet($arrResult[$shopKey][$dateKey][$i][0], $shopValue, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime);
						
						$stLine = $stDetail->getDetail($arrResult[$shopKey][$dateKey][$i][0]);
						if($stLine['a'] == 9){
						
							$stDetail->reActiveStaff($stLine['id']);
							$stInfo->activeStaff($stLine['id']);
						}
						
					}

				}
				
				}
		
			}
			
			}
		}		
		
		if($overBudget){
			
			//$arrShops = unserialize(base64_decode($_POST['shops']));
			//d($_POST);
			$obLog = new Model_Hr_Overbudgetlog();
			$subject = "Over Budge Request Approval";
			
			$mailBody = "";	
			
			$mail = new Model_Emailshandler();
			$shopHead = new Model_DbTable_Shoplocation();
			
			foreach ($_POST['reason'] as $key => $v){
				$btHour = $_POST['week_budget_hour'][$key];
				$toHour = $_POST['week_total_hour'][$key];
				$trHour = $_POST['week_total_tr_hour'][$key];
				$trBtHour = $_POST['week_budget_tr_hour'][$key];
				
				$ext = $toHour - $btHour;
				$trExt = $trHour - $trBtHour;
				
				$reasons = str_replace("|","<br />",$v);
				
				$mailBody = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} , Exceed Hours {$ext}, Trainee Budget is {$trBtHour} and Allocated Hour is {$trHour} ,Exceed Hour is {$trExt} For the Following Reason [{$reasons}] , On Week Begin {$dateBegin},Please Go to Page to Approval It.";
				if($ext <= 0){
					
					$mailBody = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} ,Trainee Hour Has Exceed the Budget, Trainee Budget is {$trBtHour} and Allocated Hour is {$trHour} ,Exceed Hour is {$trExt}  For the Following Reason [{$reasons}] , On Week Begin {$dateBegin},Please Go to Page to Approval It.";
					
				}
				$mailBodyApp = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} , Exceed Hours {$ext}, Trainee Budget is {$trBtHour} and Allocated Hour is {$trHour} ,Exceed Hour is {$trExt} ,On Week Begin {$dateBegin},Has Been Approved";
				$mailBodyRej = "SHOP {$arrShops[$key]} Budget Hours is {$btHour} and Allocated Hours is {$toHour} , Exceed Hours {$ext}, Trainee Budget is {$trBtHour} and Allocated Hour is {$trHour} ,Exceed Hour is {$trExt}  On Week Begin {$dateBegin},Has Been Rejected, You must Fix It";
				
				if($appr == -1){
					$mail->sendActionEmail("simon.seop@phonecollection.com.au", $subject, $mailBody);
					//$mail->sendNormalEmail("office@phonecollection.com.au;simon.seop@phonecollection.com.au", $subject, $mailBody);
					echo "Email Sent To HQ, Log Saved";
					$obLog->initOverbudgetlog($arrShops[$key], $dateBegin, $dateEnd, $reasons,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(), $appr,$ext,$trExt);
					
				}
				
				$shopEmail = $shopHead->getShopMailByHead($arrShops[$key]);
				
				if($appr == 1){
					
					$idObLine = $obLog->getByShop($arrShops[$key], $dateBegin, $dateEnd);
					$obLog->updateStatus($idObLine['id_overbudget'], $appr,4,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow());
					
					$mail->sendNormalEmail($shopEmail,"Your Over Budget Request Has Been Approved", $mailBodyApp);
					echo "Email Sent To Shop, Log Saved For :".$shopEmail;
					
				}
				
				if($appr == -2){
					
					$idObLine = $obLog->getByShop($arrShops[$key], $dateBegin, $dateEnd);
					$obLog->updateStatus($idObLine['id_overbudget'], $appr,4,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow());
					
					$mail->sendNormalEmail($shopEmail,"Your Over Budget Request Has Been Rejected", $mailBodyRej);
					echo "Email Sent To Shop, Log Saved For : ".$shopEmail;
				
				}
				
			}
			
		
		}
		
		}
	}

	/**
	 * @author Leo
	 * @version 2015-07-01
	 * New Arrange Roster
	 */
	public function saveArrangeRoster2015Action(){
	

		$arrResult = $_POST["arr_Detail"];
		$arrShops = unserialize(base64_decode($_POST["shops"]));
	
		$dateBegin = $_POST["date_begin"];
		$dateEnd = Model_DatetimeHelper::adjustDays("add", $dateBegin, 6);
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		
		$ts = new Model_DbTable_Roster_Timesheet();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stInfo = new Model_DbTable_Roster_Staffinfo();

		$appr = -1;
	
		foreach($arrShops as $shopKey => $shopValue){
			foreach($arrDate as $dateKey => $dateValue){
				if(isset($arrResult[$shopKey][$dateKey])){
					echo $cot = count($arrResult[$shopKey][$dateKey]);//
	
					for($i=0;$i<$cot;$i++){
						
						if(is_numeric($arrResult[$shopKey][$dateKey][$i][5])){// Update arrange roster
								//echo "exist";//
							$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
							$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
							$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
	
							$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
							$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);

							$ts->managerConfirmArrangeTimeSheet($arrResult[$shopKey][$dateKey][$i][5], $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$appr);
					
							$stLine = $stDetail->getDetail($arrResult[$shopKey][$dateKey][$i][5]);
							if($stLine['a'] == 9){
	
								$stDetail->reActiveStaff($stLine['id']);
								$stInfo->activeStaff($stLine['id']);
							}

						}
						
						if(substr($arrResult[$shopKey][$dateKey][$i][5],0,3)=="new"){ //new arrange roster
							
							$strDateBegin  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][1].":".$arrResult[$shopKey][$dateKey][$i][2];
							$strDateEnd  = $dateValue." ".$arrResult[$shopKey][$dateKey][$i][3].":".$arrResult[$shopKey][$dateKey][$i][4];
							$intBreakTime = $arrResult[$shopKey][$dateKey][$i][6]*60;
	
							$intConfirmShiftBegin =($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateBegin) :Model_DatetimeHelper::tranferToInt($strDateBegin);
							$intConfirmShiftEnd = ($shopValue == "CLPC" || $shopValue == "CLIC" || $shopValue == "ADPC" || $shopValue == "WLIC" )?Model_DatetimeHelper::tranferToIntAde($strDateEnd) :Model_DatetimeHelper::tranferToInt($strDateEnd);

							$ts->managerArrangeTimesheet($arrResult[$shopKey][$dateKey][$i][0], $shopValue, $intConfirmShiftBegin, $intConfirmShiftEnd, $intBreakTime,$appr);

							$stLine = $stDetail->getDetail($arrResult[$shopKey][$dateKey][$i][0]);
								if($stLine['a'] == 9){
	
									$stDetail->reActiveStaff($stLine['id']);
									$stInfo->activeStaff($stLine['id']);
								}
	
	
						}
	
					}
	
				}
						
			}
		}

	}
	
	
	/**
	 * Add special roster for shop staff if apply leave but actually have login
	 @author leo
	 */
	public function addRosterInLeaveAction(){
		$leave = new Model_Hr_Staffleave();
		$dateBegin = $this->_getParam('dateBegin');
		$dateEnd = $this->_getParam('dateEnd');

		$leaveApp = $leave->listAllAcceptByPeriod($dateBegin,$dateEnd);
	
		$leaveType = unserialize(LEAVE_TYPE);
		$shop = unserialize(ARR_SHOP);
		$approvedDate = Model_DatetimeHelper::dateToday();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stf = new Model_DbTable_Roster_Staffinfo();
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		$timeSheet = new Model_DbTable_Roster_Timesheet();

		$recordList = array();
		foreach($leaveApp as $k => $v){
			$record = $attRecord->listRecordByStaffId($v['id_staff'], $v['period_start'], $v['period_start']);
			if(!empty($record)){
				$recordList[$v['id_staff']][$v['period_start']] = $record;
			}
		}
	
		$this->view->leaveList =$leaveApp;
		$this->view->recordList = $recordList;
		
		
		if(isset($_POST['submit'])){
			foreach ($_POST['submit'] as $k => $v){
				$date = $_POST['date'][$k];
				$onDutyH = $_POST['onDutyH'][$k];
				$onDutyM = $_POST['onDutyM'][$k];
				$offDutyH = $_POST['offDutyH'][$k];
				$offDutyM =$_POST['offDutyM'][$k];
				$shopHead = $_POST['shop'][$k];
				$stfId = $_POST['stfId'][$k];

				if($onDutyM == 0){
					$onDuty = $date.$onDutyH.$onDutyM."0";
				}else{
					$onDuty = $date.$onDutyH.$onDutyM;
				}
				if($offDutyM == 0){
					$offDuty = $date.$offDutyH.$offDutyM."0";
				}else{
					$offDuty = $date.$offDutyH.$offDutyM;
				}
				
				if($shopHead=="ADPC" || $shopHead=="CLPC"|| $shopHead=="CLIC"|| $shopHead=="WLIC" ){
					$intOnDuty =  Model_DatetimeHelper::tranferToIntAde($onDuty);
					$intOffDuty = Model_DatetimeHelper::tranferToIntAde($offDuty);
				}else{
					$intOnDuty =  Model_DatetimeHelper::tranferToInt($onDuty);
					$intOffDuty = Model_DatetimeHelper::tranferToInt($offDuty);
				}

				  $timeSheet->addTimesheet($stfId, $shopHead, $intOnDuty, $intOffDuty);
				 $leave->updateSpRoster($k);
			}
			$url = "/roster/add-roster-in-leave";
			$this->_redirect($url);
		}
	}
	
	/**
	 * shop selection is the landing page for manager to arrange roster 
	 * check performance and create case 
	 * the manager id may need update 
	 */
	public function shopSelectionAction(){
		
		$loginSuccess = false;
	
		$arrShopList = unserialize(ARR_MANAGER);
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$sort = array();
		
		if($_POST){
			
			$pwd = $_POST["password"];
			
			$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($pwd)));
			//var_dump($stLine);
			if($stLine){
				if(isset($arrShopList[$stLine["id"]])){
					
				$sort = $arrShopList[$stLine["id"]];
				sort($sort);
				$this->view->spList = $sort;	
				$this->view->idMgr = base64_encode(trim($stLine["id"]));
				$loginSuccess = true;
				}
				else{
					$loginSuccess = false;
					echo '<script language="javascript"> window.alert("According Your Password, You are Not a Manager, Please try TYPE IN password again!")</script>';
				}
			}
			else{
				$loginSuccess = false;
				echo '<script language="javascript"> window.alert("Incorrect Password, Please try your password again")</script>';
				
			}
			
		}
		
		$this->view->loginSuccess = $loginSuccess;
		
		if(1){
			
			$this->renderScript("/roster/shop-selection-140320.phtml");
		}
	}
	

	public function zNOUSEnewStaffVerifyDoneAction(){
		
	}

	/**
	 * page in company info page to check staff own roster 
	 */
	public function checkMyRosterAction(){
		
		$staff = $this->_getParam("staff");
		$idStaff = Model_EncryptHelper::getSslpassword(base64_decode($staff));
		$dateBegin = Model_DatetimeHelper::getThisWeekMonday();
		$dateEnd = Model_DatetimeHelper::adjustWeeks("add",Model_DatetimeHelper::getThisWeekSunday(),3);
		$tList = array();
		
		$ts = new Model_DbTable_Roster_Timesheet();
		
		if(is_numeric($idStaff)){
		$tList = $ts->listShiftByStaffIdByDate($idStaff, $dateBegin, $dateEnd);
	
		$arrSb = array();
		foreach($tList as $key => $v){
			$arrSb[$key] = $v["arra_shift_begin"];
		}
		
		array_multisort($arrSb,SORT_ASC,$tList);
		}
		$this->view->tList = $tList;
		
	}
	/**
	 * roster for manager has time limits it must suit the shopping center openin hours
	 * this page give warehouse special rights to insert a whatever type of roster 
	 */
	public function saveSuTimesheetAction(){
		
		//date_default_timezone_set("Australia/Melbourne");
		
		//var_dump($_POST);
		
		$ts = new Model_DbTable_Roster_Timesheet();
		
		$shiftBegin = trim($_POST["date"])." ".$_POST["shift_start_hour_1"].":".$_POST["shift_start_min_1"];
		$shiftEnd =  trim($_POST["date"])." ".$_POST["shift_end_hour_1"].":".$_POST["shift_end_min_1"];
		
		$intShiftBegin = Model_DatetimeHelper::tranferToInt($shiftBegin);
		$intShiftEnd =  Model_DatetimeHelper::tranferToInt($shiftEnd);
		
		if($_POST["shop_code"]=="ADPC" || $_POST["shop_code"]=="CLPC"|| $_POST["shop_code"]=="CLIC"|| $_POST["shop_code"]=="WLIC" ){
			
			$intShiftBegin = Model_DatetimeHelper::tranferToIntAde($shiftBegin);
			$intShiftEnd =  Model_DatetimeHelper::tranferToIntAde($shiftEnd);	
		}

		$ts->addSuTimesheet($_POST["staff_name_1"],$_POST["shop_code"], $intShiftBegin, $intShiftEnd);
		
	}
	
	
	/**
	 * this page is for manager to check his own shop attendance record
	 */
	
	public function managerCheckAttnRecordAction(){

		$shop = $this->_getParam("shop");
		$dateBegin = $this->_getParam("db");
		$dateEnd = $this->_getParam('dn');
		
		$arrShop = unserialize(base64_decode($shop));
		
		
		if($_POST){

			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			$arrShop = $_POST['shop_selection'];
		}
				
		
		$this->view->arrDate = $arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		
		$this->view->arrShop = $arrShop;
	
		
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		
		$arrRes = array();
		$arr = array();
		
		
		foreach($arrDate as $dateToCheck){
	
			
			foreach($arrShop as $shopKey => $shopCode){
				date_default_timezone_set("Australia/Melbourne");
				
				if($shopCode == "ADPC" || $shopCode == "CLPC" ||$shopCode == "CLIC" ||$shopCode == "WLIC"  ){
					date_default_timezone_set("Australia/Adelaide");
				}
				
				$tList = $attRecord->getOndutyByDateByShop($shopCode, $dateToCheck);
				if(!empty($tList)){
				foreach($tList as $k => $v1){

					$arrRecord = $attRecord->getFirstOnLastOffDuty($v1["sti"], $dateToCheck,Model_EncryptHelper::sslPassword($shopCode));

					$begin = "[N/A]";
					$end = "[N/A]";
						

							if( $arrRecord[0] != "" ){
							$begin = date("H:i",$arrRecord[0]);
							}
							if( $arrRecord[1] != "" ){
								$end = date("H:i",$arrRecord[1]);
							}

					$arrRes[$v1["sti"]][] = array($dateToCheck,$shopCode,$begin,$end);		
				}

				}
				
			}
			
		}
		ksort($arrRes);
	
		//d($arrRes);
		$this->view->arrRes = $arrRes;
	}
	
	/**
	 * New staff registeration step 1
	 */
	public function startHereAction(){
		$this->view->shop = $this->_getParam("shop");
	}
	
	/**
	 * New staff registeration step 2
	 */
	public function registrationAction(){
		
		$errorFlag = false;
		$arrManagerID = unserialize(ARR_MANAGER);
		
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stInfoDetail = new Model_DbTable_Roster_Staffinfo();
		
		
		$shop = $_POST['shop'];
		$mgrPwd = $_POST['mgr_pwd'];
		$this->view->email = $_POST['email_addr'];
		
		if($stInfoDetail->checkEmailExist($_POST['email_addr'])){
			
			$errorFlag = true;
			echo "Email Already Exist";
		}
		$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($mgrPwd));
		if($stLine){
			if(!array_key_exists($stLine['id'], $arrManagerID)){
				$errorFlag = true;
				echo "You are not a manager";
		
			}
			else{
				
				$this->view->shopManager = base64_encode(serialize($stLine['id']));
				$this->view->shop = $shop;
			}
		}else{
			$errorFlag = true;
			echo "Wrong Password";
		}
		
		$this->view->errorFlag = $errorFlag;
		
	}
	/**
	 * new staff registration step 3
	 * latest update on 201502024 ,now sending new rate to simon 
	 */
	public function registrationDoneAction(){
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stInfoDetail = new Model_DbTable_Roster_Staffinfo();
		$email = new Model_Emailshandler();
		
		$normalRate = 16;
		$type = 5;
		
		
		
		if($_POST){
			$givenName = strtolower(trim(str_replace(" ","",$_POST["given_name"])));
			$surName =  strtolower(trim(str_replace(" ","",$_POST["surname"])));
			
			$name = Model_EncryptHelper::sslPassword($givenName." ".$surName);
			$dob = $stDetail->formateDob($_POST["year"],$_POST["month"],$_POST["day"]);
			$init = substr(trim($_POST["surname"]),0,1);
			$ascii = ord(strtolower($init)) - 96;
			$lastLogin = date("U");
			$ip = $_SERVER['REMOTE_ADDR'];
			$emailStaff = $_POST['email_addr'];

			
			
			// Get Infos
			// put into DB
			
			$idMgr = unserialize(base64_decode(trim($_POST['shop_manager'])));
			
			$shopCode = $_POST['shop'];

			if(!empty($idMgr)){
			$nameMgr = $stDetail->getDetail($idMgr);
			
			$visaDate = $_POST['visa_date'];
			
			if(!empty($_POST['pre_name'])){
				$idStaff = $stDetail->addDetail($name, Model_EncryptHelper::sslPassword($dob), $ascii,null, $lastLogin,'token', $ip,1,trim($_POST['pre_name']));
			}else{
				$idStaff = $stDetail->addDetail($name, Model_EncryptHelper::sslPassword($dob), $ascii,null, $lastLogin,'token', $ip,1,$givenName);
			}
			$stDetail->updateExpireDate(Model_DatetimeHelper::adjustDays("add",Model_DatetimeHelper::dateToday(),14), $idStaff);
			
			if($_POST['permanent']){
				$visaDate = $_POST['permanent'];
			}
			
			if($idMgr == 110){
				$stInfoDetail->addStaffinfo($idStaff,ucfirst($givenName),ucfirst($surName),trim($_POST['gender']),$idStaff."-".trim($_POST['pre_name']), 0,0, trim($emailStaff), trim($_POST['mobile_no']), trim($_POST['addr']),trim($_POST['suburb']) ,trim($_POST['state']), trim($_POST['post_code']),"", -1,$idMgr,1);
				$stInfoDetail->updatePersonalDatawithPosition($idStaff, $_POST['passport_no'],$_POST['driver_license'], $_POST['visa_type'], $visaDate,$_POST['tfn_no'],$_POST['bank_bsb'],$_POST['bank_acc_no'],$_POST['bank_acc_name'],8, $_POST['card_no'], $_POST['medicare_no'], $_POST['student_no']);
			}else{
				$stInfoDetail->addStaffinfo($idStaff,ucfirst($givenName),ucfirst($surName),trim($_POST['gender']),$idStaff."-".trim($_POST['pre_name']), 0,0, trim($emailStaff), trim($_POST['mobile_no']), trim($_POST['addr']),trim($_POST['suburb']) ,trim($_POST['state']), trim($_POST['post_code']),"", -1,$idMgr);
				$stInfoDetail->updatePersonalDatawithPosition($idStaff, $_POST['passport_no'],$_POST['driver_license'], $_POST['visa_type'], $visaDate,$_POST['tfn_no'],$_POST['bank_bsb'],$_POST['bank_acc_no'],$_POST['bank_acc_name'],1, $_POST['card_no'], $_POST['medicare_no'], $_POST['student_no']);
			}
			
			
			// add expire date 7+
			
			
			//$stInfoDetail->addStaffinfo($idStaff, $fistName, $lastName, $idCard, $idRecord, $emailStaff, $activeStaff);
			
		// Send email to Frannie
			/**
		 	 * Begin to handling rate issue 
		 	 * if it is normal rate just add into new rate 
		 	 * if it is special rate , give a link to simon so he can  update 
		 	 * until he update the link the new rate remain 0
		 	 *  
		 	 */
			if($_POST['rate'] == 'normal'){
				
				$stInfoDetail->updatePaymentInfo($idStaff,0,null,$normalRate,Model_DatetimeHelper::dateToday());
				$stInfoDetail->updateStaffType($idStaff, 5);

				$email->sendNewStaffEmailWithRate(trim($_POST['given_name']), trim($_POST['surname']), trim($_POST['gender']), $emailStaff,trim($_POST['pre_name']),trim($_POST["year"])."-".trim($_POST["month"])."-".trim($_POST["day"]), trim($_POST['addr']),trim($_POST['suburb']) ,trim($_POST['state']), trim($_POST['post_code']),trim($_POST['mobile_no']), $shopCode, $nameMgr['ni'],$idStaff,$_POST['rate'],$normalRate);
				
				
			}
			
			if($_POST['rate'] == 'special'){
				$stInfoDetail->updateStaffType($idStaff, 5);
				$stInfoDetail->updatePaymentInfo($idStaff,0,null,0,Model_DatetimeHelper::dateToday());	
				$email->sendNewStaffEmailWithRate(trim($_POST['given_name']), trim($_POST['surname']), trim($_POST['gender']), $emailStaff,trim($_POST['pre_name']),trim($_POST["year"])."-".trim($_POST["month"])."-".trim($_POST["day"]), trim($_POST['addr']),trim($_POST['suburb']) ,trim($_POST['state']), trim($_POST['post_code']),trim($_POST['mobile_no']), $shopCode, $nameMgr['ni'],$idStaff,$_POST['rate'],$_POST['sp_rate']);
				
			}
			
			
		$email->sendNewStaffEmail(trim($_POST['given_name']), trim($_POST['surname']), trim($_POST['gender']), $emailStaff,trim($_POST['pre_name']),trim($_POST["year"])."-".trim($_POST["month"])."-".trim($_POST["day"]), trim($_POST['addr']),trim($_POST['suburb']) ,trim($_POST['state']), trim($_POST['post_code']),trim($_POST['mobile_no']), $shopCode, $nameMgr['ni'],$idStaff);
		$email->sendingWelomeLetter($emailStaff, trim($_POST['given_name']),trim($_POST['surname']));		
		// redirect to setup  page
			 			
			
		// create upload link sha  
			}else{
				echo '<script language = "javascript" > alert("You are not on a manager ");</script>';
			}
		}
		
		
		
	}
	
	/**
	 * in company info page 
	 * after login , it show you what is your bonus 
	 */
	
	public function checkMybonusAction(){
		
		$idStaff = Model_EncryptHelper::getSslPassword(base64_decode($this->_getParam("sid")));
		date_default_timezone_set("Australia/Melbourne");
		$Date = date('Y-m-d', time());
		$bos = new Model_Payroll_Staffbonus();
		
		$bList = $bos->listReleasedBonus($idStaff,$Date);
		$this->view->bList = $bList; 
		
		
	}
	
	//20140605
	/**
	 * this funcion is not in good use 
	 * this function should export the roster in Excel format 
	 */
	public function exportRosterAction(){
		
		//$dateBegin = $this->_getParam("date_begin");
		//$dateEnd = $this->_getParam("date_end");
		
		$dateBegin = $_POST['date_begin'];
		$dateEnd = $_POST['date_end'];
		$arrShop = $_POST['shop_selection'];
		
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		$staff = new Model_DbTable_Roster_Stafflogindetail();
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		
		$shops = $this->_getParam("shops");
		
		//$arrShop = unserialize(base64_decode($shops));
		
		$ts = new Model_DbTable_Roster_Timesheet();
		
		$arrRes = array();
		$arr = array();
		$myarray = array();
		$whArray = array();
		
		
		foreach($arrShop as $shop){

			date_default_timezone_set('Australia/Melbourne');
			
			if($shop == "ADPC" || $shop == "CLPC" || $shop == "CLIC" || $shop == "WLIC" ){
				date_default_timezone_set('Australia/Adelaide');
			}
			
			foreach($arrDate as $dateToCheck){
				$arrRes[$shop][$dateToCheck] = $tsLines = $ts->listShiftByDateByShop($shop, $dateToCheck, $dateToCheck);
				foreach($tsLines as $tsLine){
					$sdLine = $staff->getDetail($tsLine['id_staff']);
					
					$showName = ($sdLine['ni']=="") ? ucwords(Model_EncryptHelper::getSslPassword($sdLine['n'])) : ucwords($sdLine['ni']).".".strtoupper(chr($sdLine['il']+96));
					//$arrRecord = $attRecord->getFirstOnLastOffDuty($tsLine["sti"], $dateToCheck,Model_EncryptHelper::sslPassword($shopCode));
					
					$begin = $tsLine['arra_shift_begin'];
					$end = $tsLine['arra_shift_end'];
					if($tsLine['shop_head'] == 'WHCH'){
						$whArray[$showName][] = array($dateToCheck,$shop,$tsLine['shift_begin'],$tsLine['shift_end']);
					}
				}
				if($begin != $end){
				$myarray[$showName][] = array($dateToCheck,$shop,$begin,$end);
				}
				

				
				/*
				$arrRes[$shop][$dateToCheck] = $tsLines = $ts->listShiftByDateByShop($shop, $dateToCheck, $dateToCheck);
				echo $dateToCheck." : ";

			
				foreach($tsLines as $tsLine){
					$sdLine = $stDetail->getDetail($tsLine['id_staff']);
				echo	$showName = ($sdLine['ni']=="") ? ucwords(Model_EncryptHelper::getSslPassword($sdLine['n'])) : ucwords($sdLine['ni']).".".strtoupper(chr($sdLine['il']+96));
				//echo $tsLine['id_staff'];
				echo " ";
				echo date("H:i",$tsLine['arra_shift_begin']);
				echo " - ";
				echo date("H:i",$tsLine['arra_shift_end']);
				echo ", ";
		
				}
				
				echo "<br />";
					*/
			}
				
		}
		ksort($myarray);
		//d($whArray);
		foreach($myarray as $key =>$v){
			echo $key.'<br>';
			foreach($v as $d){
				echo $d[1].' ';
				echo $d[0].' '.date("H:i",$d[2]). " - ". date("H:i",$d[3]).'<br>';
			}
		
		}
		if($whArray){
			foreach($whArray as $key =>$v){
				echo $key.'<br>';
				foreach($v as $d){
					echo $d[1].' ';
					echo $d[0].' '.date("H:i",$d[2]). " - ". date("H:i",$d[3]).'<br>';
				}
			
			}
		}
		
		//d($arrRes);
		
	}
	//140613
	
	/**
	 * This function is for auto send notice email for staff traning > 21 days
	 * but position is still traning
	 */
	public function checkStaffStatusAction(){
		
		set_time_limit(10000);
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$today = Model_DatetimeHelper::dateToday();
		$mail = new Model_Emailshandler();
			
		$registerDate = array();
		
		$allStaff = $stInfo->listAll();
		
		$receiver = '';
		$body1 = 'Hi Manager'.'<br/>'.'The following list of staff has been trained more than 21 days, please review and make your decision whether you want to keep him/her in the further in two weeks.'.'<br/>'.
		'<br/>';
		$body2 = 'Hi Manager'.'<br/>'.'The following list of staff has been trained more than 35 days, please review and make your decision whether you want to keep him/her in the further in two weeks.'.'<br/>'.
		'<br/>';
		$str = '';
		$strtemp1 ='';
		$str2 = '';
		$strtemp2 ='';
		$receiver2 = array();
		$link = 'http://'.WEB_IP.'/docs/PC_Annual_Review_Form_v81_final3.pdf'.'<br/>'.'<br/>';
		$regards = 'Regards'.'<br/>'.'Phone Collection Head Office';
		$emailArray = array(
					'156'=>'kevin.shi@phonecollection.com.au',
					'4'=>'simon.seop@phonecollection.com.au',
					'204'=>'john.chan@phonecollection.com.au',
					'165'=>'will.li@phonecollection.com.au',
					'2'=>'hope.mcmahon@phonecollection.com.au',
					'131'=>'jason.han@phonecollection.com.au',
					'110'=>'eco3@phonecollection.com.au',
					'36'=>'ting.chow@phonecollection.com.au',
					'125'=>'catherine.ho@phonecollection.com.au',
					'115'=>'iris.kim@phonecollection.com.au',
					'27'=>'terra.yu@phonecollection.com.au',
					'3'=>'adele.ye@phonecollection.com.au',
					'162'=>'kelly.li@phonecollection.com.au'
				);
		
		foreach($allStaff as $key => $v){
			if($v['register_date']!= null && $v['position_status'] == '1'&& $v['leave_check'] == null){
				$registerDate[] = $v['register_date'];
				foreach ($registerDate as $key => $vd){
					$reg = strtotime($vd);
					$extend = ((strtotime($today)) - $reg)/86400;
				}
				if($extend>=21 && $extend<35){
					$manger = $v['id_manager_introduce'];
					$receiver = $emailArray[$manger];
					
					$str = '<tr>'.'<td>'.$v['first_name'].'.'.$v['last_name'].'</td>'.'<td>'.$v['register_date'].'</td>'.'</tr>';
					$strtemp1 .= '<tr>'.'<td>'.$v['first_name'].'.'.$v['last_name'].'</td>'.'<td>'.$v['register_date'].'</td>'.'</tr>'.'<br/>';
						$mail->sendNormalEmail($receiver,"The requirements for training staff review",$body1.'<table>'.'<tr>'.'<td>'.'Name:'.'</td>'.'<td>'.'Register date:'.'</td>'.'</tr>'.$str.'</table>'.'<br/>'.'The link of review rule as below.'.'<br/>'.$link.$regards);
				}
				if($extend >= 35){
					$manger = $v['id_manager_introduce'];
					$receiver = $emailArray[$manger];
					$str2 = '<tr>'.'<td>'.$v['first_name'].'.'.$v['last_name'].'</td>'.'<td>'.$v['register_date'].'</td>'.'</tr>';
					$strtemp2 .= '<tr>'.'<td>'.$v['first_name'].'.'.$v['last_name'].'</td>'.'<td>'.$v['register_date'].'</td>'.'<td>'.$receiver.'</td>'.'</tr>'.'<br/>';
						$mail->sendNormalEmail($receiver,"The requirements for training staff review",$body2.'<table>'.'<tr>'.'<td>'.'Name:'.'</td>'.'<td>'.'Register date:'.'</td>'.'</tr>'.$str2.'</table>'.'<br/>'.'The link of review rule as below.'.'<br/>'.$link.$regards);
				}
					
			}
			
		}	
		if($strtemp1!=''){
			echo 'Staff Traning > 3 weeks List'.'<br/>';
			echo $strtemp1;
			echo "Email has been sent".'<br/>'.'<br/>';
		}
		if($strtemp2!=''){
			echo 'StaffTraning > 5 weeks List'.'<br/>';
			echo $strtemp2;
			$mail->sendNormalEmail('office@phonecollection.com.au',"The requirements for training staff review",$body2.'<table>'.'<tr>'.'<td>'.'Name:'.'</td>'.'<td>'.'Register date:'.'</td>'.'<td>'.'Manager Email'.'</td>'.'</tr>'.$strtemp2.'</table>'.'The link of review rule as below.'.'<br/>'.$link.$regards);
			echo "Email has been sent".'<br/>';
		}
	}
	
	
	/**
	 * 1.For check all staff visa expire status, if so notice manager
	 * 2. Check all full-time, part-time staff for notice 
	 * @version 2014-08-01
	 * @author Leo
	 */
	public function checkVisaExpireAction(){
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$today = Model_DatetimeHelper::dateToday();
		$mail = new Model_Emailshandler();
		$allStaff = $stInfo->listAll();
		$list = array();
		foreach($allStaff as $k => $v){
			$tmpArr = array();
			$tmpArr = $v;
			$tmpArr['visa_date'] = Model_EncryptHelper::getSslPassword($v['visa_date']);
			$list[] = $tmpArr;
		}
		$receiver = '';
		$body1 = 'Hi Manager'.'<br/>'.'The following list of staff visa has expired, please check visa status of them.'.'<br/>'.
				'<br/>';
		$body2 = 'Hi Manager'.'<br/>'.'The following list of staff need a half year review.'.'<br/>'.
				'<br/>';
		$str = '';
		$str2 = '';
		$strtemp1 ='';
		$strtemp2 ='';
		$regards = 'Regards'.'<br/>'.'Phone Collection Head Office';
		$emailArray = array(
				'156'=>'kevin.shi@phonecollection.com.au',
				'4'=>'simon.seop@phonecollection.com.au',
				'204'=>'john.chan@phonecollection.com.au',
				'165'=>'will.li@phonecollection.com.au',
				'2'=>'hope.mcmahon@phonecollection.com.au',
				'131'=>'jason.han@phonecollection.com.au',
				'110'=>'eco3@phonecollection.com.au',
				'36'=>'ting.chow@phonecollection.com.au',
				'125'=>'catherine.ho@phonecollection.com.au',
				'115'=>'iris.kim@phonecollection.com.au',
				'27'=>'terra.yu@phonecollection.com.au',
				'3'=>'adele.ye@phonecollection.com.au',
				'162'=>'kelly.li@phonecollection.com.au'
		);

		$checklist = array();
		foreach($list as $k2 => $v2){
			$tmpArr2 = array();
			if($v2['visa_date2']!=null){
				if($v2['visa_date2'] < $today){
					$manager = $v2['id_manager_introduce'];
					$receiver = $emailArray[$manager];
					$tmpArr2 = $v2;
					$checklist[] = $tmpArr2;
				
					$str = '<tr>'.'<td>'.$v2['first_name'].'.'.$v2['last_name'].'</td>'.'<td>'.$v2['visa_date2'].'</td>'.'</tr>';
					$strtemp1 .= '<tr>'.'<td>'.$v2['first_name'].'.'.$v2['last_name'].'</td>'.'<td>'.$v2['visa_date2'].'</td>'.'</tr>'.'<br/>';
					//$mail->sendNormalEmail($receiver,"The staff visa expired or miss list",$body1.'<table>'.'<tr>'.'<td>'.'Name:'.'</td>'.'<td>'.'Visa date:'.'</td>'.'</tr>'.$str.'</table>'.'<br/>'.$regards);
				}
			}
		}
		//if($strtemp1!= null){
			//$mail->sendNormalEmail('office@phonecollection.com.au',"The staff visa expired or miss list",$body1.'<table>'.'<tr>'.'<td>'.'Name:'.'</td>'.'<td>'.'Visa date:'.'</td>'.'<td>'.'Manager Email'.'</td>'.'</tr>'.$strtemp1.'</table>'.$regards);
		//}
		$checklist2 = array();
		foreach($list as $k3 => $v3){
			if($v3['visa_date']!= null){
				$tmpArr3 = $v3;
				$checklist2[] = $tmpArr3;
			}
		}
		$this->view->date = $checklist2;
		$reviewList = array();
		foreach($allStaff as $k4 => $v4){
			$tmpArr4 = array();
			if($v4['register_date']!= null && $v4['position_status'] == 2 || $v4['register_date']!= null && $v4['position_status'] == 3){
				$reg = strtotime($v4['register_date']);
				$extend = (int)(((strtotime($today)) - $reg)/86400);
				if($extend%180 == 0 && $extend >= 180){
					$tmpArr4 = $v4;
					$manager = $v4['id_manager_introduce'];
					$receiver = $emailArray[$manager];
					$str2 = '<tr>'.'<td>'.$v4['first_name'].'.'.$v4['last_name'].'</td>'.'<td>'.$v4['register_date'].'</td>'.'</tr>';
					$strtemp2 .= '<tr>'.'<td>'.$v4['first_name'].'.'.$v4['last_name'].'</td>'.'<td>'.$v4['register_date'].'</td>'.'</tr>'.'<br/>';
					//$mail->sendNormalEmail($receiver,"Staff half year review list",$body2.'<table>'.'<tr>'.'<td>'.'Name:'.'</td>'.'<td>'.'Register date:'.'</td>'.'</tr>'.$str2.'</table>'.'<br/>'.$regards);
					$reviewList[] = $tmpArr4;
				}
			}
		}

	}
	
	/**
	 * This function is for staff apply online leave application
	 * Into this page after login
	 @author leo
	 */
	public function onlineLeaveApplicationFormAction(){
		$get = $this->_getParam("sId");
		$shopHead = $this->_getParam("shop");
		$stf = new Model_DbTable_Roster_Staffinfo();
		$stfD = new Model_DbTable_Roster_Stafflogindetail();
		$sId = Model_EncryptHelper::getSslpassword(base64_decode($get));
		$dateToday = Model_DatetimeHelper::dateToday();
		$mail = new Model_Emailshandler();
		$leave = new Model_Hr_Staffleave(); 
		$stfDetail = $stf->getStaffinfo($sId);
		$nickName = $stfD->getDetail($sId);
		$check1 = false;
		$check2 = false;
		error_reporting(E_ALL ^ E_NOTICE);
		$emailArray = array(
				156=>array('Kevin','kevin.shi@phonecollection.com.au'),
				4=>array('Simon','simon.seop@phonecollection.com.au'),
				204=>array('John','john.chan@phonecollection.com.au'),
				165=>array('Will','will.li@phonecollection.com.au'),
				2=>array('Hope','hope.mcmahon@phonecollection.com.au'),
				131=>array('Jason','jason.han@phonecollection.com.au'),
				110=>array('HeadOffice','admin@phonecollection.com.au'),
				36=>array('Ting','ting.chow@phonecollection.com.au'),
				125=>array('Catherine','catherine.ho@phonecollection.com.au'),
				115=>array('Iris','iris.kim@phonecollection.com.au'),
				27=>array('Terra','terra.yu@phonecollection.com.au'),
				3=>array('Adele','adele.ye@phonecollection.com.au'),
				162=>array('Kelly','kelly.li@phonecollection.com.au')
		);
		
		$type = array(1=>'Annual Leave',
         			  2=>'Sick Leave',
         			  3=>'Long Service Leave',
        			  4=>'Unpaid Leave',
          			  5=>'Other Leave');
		
		if(array_key_exists($stfDetail['id_manager_introduce'], $emailArray)){
			$managerName = $emailArray[$stfDetail['id_manager_introduce']][0];
			$mEmail = $emailArray[$stfDetail['id_manager_introduce']][1];
		}else{
			$managerName = $emailArray[110][0];
			$mEmail = $emailArray[110][1]; 
		}
		 
		$this->view->manager = $managerName;
		$this->view->staffName = $stfDetail['first_name']." ".$stfDetail['last_name'];
		$this->view->check = false;
		
		if(isset($_POST['submit'])){
			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			$this->view->dateBegin = $dateBegin;
			$this->view->dateEnd = $dateEnd;
			$this->view->check = true;

			
		}
		
		$dateArray = array();
		$dateSort = array();
		$hrArray = array();
		$totalHr = 0;
		if(isset($_POST['btn_save'])){
			$leaveType = $_POST['leave_type'];
			$dateApply = Model_DatetimeHelper::dateToday();
			foreach ($leaveType as $k => $v){
				if(!empty($v)){
					$dateArray[$k] = array($v,$_POST['date_time'][$k],$_POST['leave_start_hour'][$k],$_POST['leave_end_hour'][$k],$_POST['leave_hr'][$k],$_POST['leave_comm'],$_POST['leave_start_min'][$k],$_POST['leave_end_min'][$k]);
					$dateSort[] = $_POST['date_time'][$k];
					$hrArray[$_POST['date_time'][$k]] =$_POST['leave_hr'][$k];
					$totalHr += $_POST['leave_hr'][$k];
				//
			
				}
			}
			
			arsort($dateSort);
			array_multisort($dateSort,SORT_ASC,$dateArray);
			$count = count($dateSort)-1;
			$startLeaveDate = $dateSort[0];
			$endLeaveDate = $dateSort[$count];

		
			$dateCheck = Model_DatetimeHelper::createDateArray($startLeaveDate, $endLeaveDate);
			array_unshift($dateCheck, null);
			unset($dateCheck[0]);
			$diff = Model_DatetimeHelper::dateDiff($startLeaveDate, $endLeaveDate);
			
			if($diff <= 14){
				$check1 = true;
			}
			
			
			$checkCount = 0;
			foreach($dateArray as $k5 => $v5){
				if($v5[4] <= 0){
					$checkCount ++;
				}
			}
			
			if($checkCount == 0){
				$check2 = true;
			}
			
			if($check1 == true && $check2 == true){
				$str = "Staff ".$stfDetail['first_name']." ".$stfDetail['last_name']."(".$nickName['ni'].")"." has applied <br/>";
				$subject = "Staff ".$stfDetail['first_name']." ".$stfDetail['last_name']."(".$nickName['ni'].")"." has applied Leave";
				$str2 = "Staff ".$stfDetail['first_name']." ".$stfDetail['last_name']."(".$nickName['ni'].")"." has applied <br/>";
				$emailCheck = array();
				foreach($dateArray as $k4 => $v4){
					$appCheck = $leave->getLeaveByIdDate($sId, $v4[1]);
					$whCheck = $stf->getStaffinfo($sId);
					if(!$appCheck){
						if($v4[1] < $dateToday){
							$leave->addStaffleave($sId, $dateApply, $shopHead,$dateToday, 2, $v4[1], $v4[1], $v4[2], $v4[6], $v4[3], $v4[7], $v4[4], $v4[5], null, null, null, null, null, null, null);
							$v4[0] = 2;
						}else{
							$leave->addStaffleave($sId, $dateApply, $shopHead,$dateToday, $v4[0], $v4[1], $v4[1], $v4[2], $v4[6], $v4[3], $v4[7], $v4[4], $v4[5], null, null, null, null, null, null, null);
						}
						
						$str .= $type[$v4[0]]." on date ".$v4[1]." Period:".$v4[2].":".str_pad($v4[6], 2, "0", STR_PAD_RIGHT)." - ".$v4[3].":".str_pad($v4[7], 2, "0", STR_PAD_RIGHT)."<br/>";
						$str2 .= $type[$v4[0]]." on date ".$v4[1]." Period:".$v4[2].":".str_pad($v4[6], 2, "0", STR_PAD_RIGHT)." - ".$v4[3].":".str_pad($v4[7], 2, "0", STR_PAD_RIGHT)."<br/>";
						$emailCheck[] = $v4[1];
						
					}else{
						$this->view->errorflag = true;
						$this->view->errorMessage = "You have applied ".$type[$v4[0]]." on date: ".$v4[1]."<br/>";
						return false;
					}
					
				}
				
				$str .= " If you have any question, please call Head Office.";
				$str2 .= " Please use below link for decision"."<br/>"."http://".WEB_IP."/roster/online-leave-confirm-application"."<br/>";
				
				if(!empty($emailCheck)){
						$mail->sendNormalEmail($stfDetail['email_staff'], $subject, "You have applied <br/>".$str."<br/>If it is not correct, please call Head Office.");
					if($whCheck['is_wh'] == 1 || $whCheck['position_status'] == 8){
						
						$mail->sendActionEmail('admin@phonecollection.com.au;phonecollection.au@gmail.com', $subject, $str2); //send to Livia & Ken
						//$mail->sendActionEmail('phonecollection.au@gmail.com',$subject, $str2);//send to Ken
					}else{
						$mail->sendNormalEmail($mEmail, $subject, $str); //send to manager
						$mail->sendActionEmail('simon.phonecollection@gmail.com', $subject, $str2); // send to Simon
					}
				}else{
					$this->view->errorflag = true;
					$this->view->errorMessage = "Invalid Application Please Check Date and Type <br/>";
					return false;
				}
				
				
				$this->view->stfId = $sId;
				$this->view->staffEmail = $stfDetail['email_staff'];
				$this->renderScript('/roster/onlince-leave-application-done.phtml');
			}else{
				if($check1 != true && $check2 != true){
					$this->view->errorflag = true;
					$this->view->errorMessage = "You can not apply continuous 15 Days/Your apply hour cannot < 0";
					return false;
				}
				elseif($check1 != true){
					$this->view->errorflag = true;
					$this->view->errorMessage = "You can not apply continuous 15 Days";
					return false;
				}elseif($check2 != true){
					$this->view->errorflag = true;
					$this->view->errorMessage = "Your apply hour cannot < 0";
					return false;
				}
			}
			
		}
		
		if(isset($_POST['update_email'])){
			$stfId = $_POST['stf_id'];
			$email = $_POST['correct_email'];
			if($stfId && $email){
				$stf->updateStaffEmail($stfId, $email);
			}
			$this->view->stfId = $stfId;
			$this->view->staffEmail = $email;
			$this->renderScript('/roster/onlince-leave-application-done.phtml');
		}
		
	}
	
	/**
	 * This function is for approve online leave application
	 * only Simon/Ken/Livia can approve case
	 @author leo
	 */
	
	public function onlineLeaveConfirmApplicationAction(){
		$leave = new Model_Hr_Staffleave();
		$leaveApp = $leave->listAll();
		$shop = unserialize(ARR_SHOP);
		$approvedDate = Model_DatetimeHelper::dateToday();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stf = new Model_DbTable_Roster_Staffinfo();
		$timeSheet = new Model_DbTable_Roster_Timesheet();
		$mail = new Model_Emailshandler();
		
		$simon = $this->_getParam("id");
		
		if($simon == 'simon'){
			$this->view->check = 'simon';
		}

		if($simon == 'ken'){
			$this->view->check = 'ken';
		}
		
		$emailArray = array(
				156=>array('Kevin','kevin.shi@phonecollection.com.au'),
				4=>array('Simon','simon.seop@phonecollection.com.au'),
				204=>array('John','john.chan@phonecollection.com.au'),
				165=>array('Will','will.li@phonecollection.com.au'),
				2=>array('Hope','hope.mcmahon@phonecollection.com.au'),
				131=>array('Jason','jason.han@phonecollection.com.au'),
				110=>array('HeadOffice','admin@phonecollection.com.au'),
				36=>array('Ting','ting.chow@phonecollection.com.au'),
				125=>array('Catherine','catherine.ho@phonecollection.com.au'),
				115=>array('Iris','iris.kim@phonecollection.com.au'),
				27=>array('Terra','terra.yu@phonecollection.com.au'),
				3=>array('Adele','adele.ye@phonecollection.com.au'),
				162=>array('Kelly','kelly.li@phonecollection.com.au')
		);
		
		$pendingCase = array();
		$acceptCase = array();
		$rejectCase = array();
		$tmppendingCase = array();
		$sort = array();
		$acceptSort = array();
	
		foreach($leaveApp as $k => $v){
			
			if($v['approved_result'] == 'accept' ){
				
				$acceptCase[] = $v;
				$acceptSort[] = $v['paid_date'];
			}else if ($v['approved_result'] == 'cancel'){
				$rejectCase[] = $v;
			}else{
				$sort[] = $v['period_start'];
				$tmppendingCase[] = $v;
			}
		}
		arsort($sort);
		array_multisort($acceptSort,SORT_ASC,$acceptCase);
		array_multisort($sort,SORT_ASC,$tmppendingCase);
		
		foreach ($tmppendingCase as $k2 => $v2){
			if($simon == 'simon'){
				$stfInfo = $stf->getStaffinfo($v2['id_staff']);
				if($stfInfo['is_wh'] != 1 && $stfInfo['position_status'] != 8){
					$pendingCase[$v2['id_staff']][] = $v2;
				}
			}
			
			if($simon == 'ken'){
				$pendingCase[$v2['id_staff']][] = $v2; 
			}
			
		}
	
		$this->view->acceptCase = $acceptCase;
		$this->view->rejectCase = $rejectCase;
		$this->view->pendingCase = $pendingCase;
		
		if(isset($_POST['next'])){
			$password = $_POST['password'];

			$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
			if(!$stLine){
						
				echo '<script>alert("Wrong Password");</script>';
			}else{
				if($stLine['id'] == 4){
					$url = "/roster/online-leave-confirm-application/id/simon";
					$this->_redirect($url);
					$this->view->check = 'simon';
				}

				if($stLine['id'] == 337){
					$url = "/roster/online-leave-confirm-application/id/simon";
					$this->_redirect($url);
					$this->view->check = 'olga';
				}
				if($stLine['id'] == 431){
					$url = "/roster/online-leave-confirm-application/id/ken";
					$this->_redirect($url);
					$this->view->check = 'ken';
				}else{
					echo '<script>alert("You do not have the permit");</script>';
				}
				
			}
			
		}
		
		if(isset($_POST['cancel'])){
			foreach($_POST['cancel'] as $k => $v){
				$leaveDetail = $leave->getStaffleave($k);
				$preTimeSheet = $timeSheet->listShiftByStaffIdByDate2($leaveDetail['id_staff'], $leaveDetail['period_start'], $leaveDetail['period_start']);
				
				$timeSheet->deleteTimesheet($preTimeSheet[0]['id_sheet']);
				$leave->deleteStaffleave($k);
			}
			$url = "/roster/online-leave-confirm-application/id/".$simon;
			$this->_redirect($url);
		}

		if(isset($_POST['accept'])){
					$mailList = array();
				foreach($_POST['checkbox'] as $k2 => $v2){
					
					$leaveApplication = $leave->getStaffleave($k2);
					$checkRoster = $timeSheet->listShiftByStaffIdByDate2($leaveApplication['id_staff'], $leaveApplication['period_start'], $leaveApplication['period_start']);
					
					if($checkRoster){
						$timeSheet->deleteTimesheet($checkRoster[0]['id_sheet']);
					}

					$shiftBegin = date("U",strtotime($leaveApplication['period_start']." ".$leaveApplication['period_start_hr'].":".$leaveApplication['period_start_min']));
					$shiftEnd = date("U",strtotime($leaveApplication['period_end']." ".$leaveApplication['period_end_hr'].":".$leaveApplication['period_end_min']));
				
						$timeSheet->addHolidayTimesheet($leaveApplication['id_staff'], $leaveApplication['shop_code'], $shiftBegin, $shiftEnd);
					if($simon == 'simon'){
						$leave->updateResult($k2, $approvedDate, 4, 'accept', null,$_POST['leave_type'][$k2]);
						$simon = 'simon';
					}

					if($simon == 'ken'){
						$leave->updateResult($k2, $approvedDate, 431, 'accept', null,$_POST['leave_type'][$k2]);
						$simon = 'ken';
					}
					
					
					$stfInfo = $stf->getStaffinfo($leaveApplication['id_staff']);
					
					$mailList[$leaveApplication['id_staff']][] = $k2;

				}
			
				if(!empty($mailList)){
					foreach ($mailList as $k3 => $v3){
						$stfInfo = $stf->getStaffinfo($k3);
						$nickName = $stDetail->getDetail($k3);
						$title = "Staff: ". $stfInfo['first_name']." ".$stfInfo['last_name']."(".$nickName['ni'].") "." leave application has approved";
						$title2 = "Your leave application as below has approved";
						$str = "Staff: ". $stfInfo['first_name']." ".$stfInfo['last_name']."(".$nickName['ni'].") "."approved leave date as below"."<br/><br/>";
						$str2 = "Your leave application as below has approved<br/><br/>";
						foreach ($v3 as $k4 => $v4){
							$leaveApplication = $leave->getStaffleave($v4);
						
							if($leaveApplication['period_start_min'] == 30){
								$str .= $leaveApplication['period_start']." from ".$leaveApplication['period_start_hr'].":".$leaveApplication['period_start_min']." ~~ ".$leaveApplication['period_end_hr'].":".$leaveApplication['period_end_min']."<br/>";
									
								$str2 .= $leaveApplication['period_start']." from ".$leaveApplication['period_start_hr'].":".$leaveApplication['period_start_min']." ~~ ".$leaveApplication['period_end_hr'].":".$leaveApplication['period_end_min']."<br/>";
							
							}else{
								$str .= $leaveApplication['period_start']." from ".$leaveApplication['period_start_hr'].":".$leaveApplication['period_start_min']."0 ~~ ".$leaveApplication['period_end_hr'].":".$leaveApplication['period_end_min']."0"."<br/>";
						
								$str2 .= $leaveApplication['period_start']." from ".$leaveApplication['period_start_hr'].":".$leaveApplication['period_start_min']."0 ~~ ".$leaveApplication['period_end_hr'].":".$leaveApplication['period_end_min']."0"."<br/>";
							
							}
							
							if($leaveApplication['approved_id_staff'] == 431){
								$approveP = 'Livia Ken';
							}elseif($leaveApplication['approved_id_staff'] == 4){
								$approveP = 'Simon';
							}
						}
							$str .= "<br/>Approved by:".$approveP."<br/>If you have arranged his/her roster, please re-arrange another person, thanks";
							$str2 .= "<br/>Approved by:".$approveP."<br/>Please check the date, if you have any question, please call headoffice";
						
						$mail->sendNormalEmail($stfInfo['email_staff'], $title2, $str2); // send to staff
						//$mail->sendNormalEmail('office@phonecollection.com.au;olga.kwan@phonecollection.com.au;phonecollection.au@gmail.com;'.$emailArray[$stfInfo['id_manager_introduce']][1], $title, $str); // send to manager
						$mail->sendNormalEmail('office@phonecollection.com.au;payroll@phonecollection.com.au;phonecollection.au@gmail.com', $title, $str); //send to carla

					}
					
				}
				
				$url = "/roster/online-leave-confirm-application/id/".$simon;
				$this->_redirect($url);
				
				
				

		}
		if(isset($_POST['reject'])){
				$mailListReject = array();
				foreach($_POST['checkbox'] as $k2 => $v2){
					if($simon == 'simon'){
						$leave->updateResult($k2, $approvedDate, 4, 'cancel', $_POST['reason'][$k2],$_POST['leave_type'][$k2]);
						$simon = 'simon';
					}
					
					if($simon == 'ken'){
						$leave->updateResult($k2, $approvedDate, 431, 'cancel', $_POST['reason'][$k2],$_POST['leave_type'][$k2]);
						$simon = 'ken';
					}
				
					$leaveApplication = $leave->getStaffleave($k2);
					$stfInfo = $stf->getStaffinfo($leaveApplication['id_staff']);
					$mailListReject[$leaveApplication['id_staff']][] = $k2;

				}
				
				foreach ($mailListReject as $k3 => $v3){
					
					$title2 = "Your leave application below has rejected";
					$str2 = "Your leave application as below has rejected<br/><br/>";
					$stfInfo = $stf->getStaffinfo($k3);
					foreach ($v3 as $k4 => $v4){
						$leaveApplication = $leave->getStaffleave($v4);
						if($leaveApplication['period_start_min'] == 30){
							$str2 .= $leaveApplication['period_start']." from ".$leaveApplication['period_start_hr'].":".$leaveApplication['period_start_min']." ~~ ".$leaveApplication['period_end_hr'].":".$leaveApplication['period_end_min']
					." has rejected"."Reason:".$leaveApplication['cancel_reason']."<br/>";		
						}else{
						$str2 .= $leaveApplication['period_start']." from ".$leaveApplication['period_start_hr'].":".$leaveApplication['period_start_min']."0 ~~ ".$leaveApplication['period_end_hr'].":".$leaveApplication['period_end_min']."0"
					." has rejected"."Reason:".$leaveApplication['cancel_reason']."<br/>";
					
						}
					}
					$str2 .= "<br/>Please check the date, if you have any question, please call headoffice";
					
					$mail->sendNormalEmail($stfInfo['email_staff'], $title2, $str2);
				}
				
				
				
				$url = "/roster/online-leave-confirm-application/id/".$simon;
				$this->_redirect($url);
			
		}
		
	}
	
	/**
	 * This function is for accounting department confirm paid annual leave case
	 @author leo
	 */
	public function onlineLeaveSummaryAction(){
		$leave = new Model_Hr_Staffleave();
		$leaveApp = $leave->listAllAcceptNoPaid();
		$leaveType = unserialize(LEAVE_TYPE);
		$payType = unserialize(PAYROLL_TYPE);
		$shop = unserialize(ARR_SHOP);
		$approvedDate = Model_DatetimeHelper::dateToday();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stf = new Model_DbTable_Roster_Staffinfo();

		$leaveList = array();
		
		foreach($leaveApp as $k => $v){
			$tmpArr = array();
			$stfDetail = $stDetail->getDetail($v['id_staff']);
			$stfInfo = $stf->getStaffinfo($v['id_staff']);
			$tmpArr['id_leave'] = $v['id_leave'];
			$tmpArr['first_name'] = $stfInfo['first_name'];
			$tmpArr['last_name'] = $stfInfo['last_name'];
			$tmpArr['ni'] = $stfDetail['ni'];
			$tmpArr['leave_time'] = $v['period_start_hr'].":".str_pad($v['period_start_min'],2,"0",STR_PAD_LEFT)." - ".$v['period_end_hr'].":".str_pad($v['period_end_min'],2,"0",STR_PAD_LEFT);

			$tmpArr['leave_date'] = $v['period_start'];	
			$tmpArr['leave_type'] = $leaveType[$v['period_type']];
			$tmpArr['leave_hour'] = $v['total_hrs'];
			$tmpArr['pay_type'] = $payType[$stfInfo['id_package']][1];
			$leaveList[$v['id_staff']][] = $tmpArr;		
			
		}

		$this->view->leaveList = $leaveList;
		
		if(isset($_POST['submit'])){
			$date = $_POST['date'];
			foreach ($_POST['leave'] as $k => $v){
				$leave->updatePaidDate($k, $date);
			}
			$url = "/roster/online-leave-summary";
			$this->_redirect($url);
		}
	}
	
	/**
	 * Auto runing function for notice online leave application
	 * not handle in 5 days
	 */
	public function onlineLeaveNoticeAction(){
		$leave = new Model_Hr_Staffleave();
		$stf = new Model_DbTable_Roster_Staffinfo();
		$stfD = new Model_DbTable_Roster_Stafflogindetail();
		$mail = new Model_Emailshandler();
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$pending = $leave->listAllPending();
		$stdPending = array();
		foreach ($pending as $k => $v){
			$stdPending[$v['id_staff']][$v['date_apply']][] = $v; 
		}
		
		foreach ($stdPending as $stfId => $dateApp){
			$stfInfo = $stf->getStaffinfo($stfId);
			$stfDetail = $stfD->getDetail($stfId);
				$title = "Please check this Annual leave application";
				$str = "Staff:".$stfInfo['first_name']." ".$stfInfo['last_name']." (".$stfDetail['ni'].") apply leave application has not confirmed yet<br/>";
				$str .= "Apply Date ".key($dateApp)."<br/><br/>";
			foreach ($dateApp as $date => $v3){
				$diff = Model_DatetimeHelper::dateDiff($date, $dateToday);
				
				if($diff > 5){
				
					foreach ($v3 as $k2 => $v2){
						$str .= "Date: ".$v2['period_start']."  Period: ".$v2['period_start_hr'].":".str_pad($v2['period_start_min'], 2, "0", STR_PAD_RIGHT)." ~~ ".$v2['period_end_hr'].":".str_pad($v2['period_end_min'], 2, "0", STR_PAD_RIGHT)."Total Hr:".$v2['total_hrs']."<br/>";
						
					}
				
				}
			}
			
			if($diff > 5){
				
				$str .= " Please use below link for decision<br/>"."http://".WEB_IP."/roster/online-leave-confirm-application"."<br/><br/>";
				if($stfInfo['is_wh'] == 1 || $stfInfo['position_status'] == 8){
					//echo $str;
		
					$mail->sendActionEmail('admin@phonecollection.com.au;phonecollection.au@gmail.com', $title, $str);

				}else{
					$mail->sendActionEmail('simon.phonecollection@gmail.com', $title, $str);
				
				}
			}
			
		}
	}
	
	/**
	 * this page is for simon to check all the trainees
	 * if simon see the trainee 
	 * he can choose pass or not pass 
	 * if pass he can change the rate 
	 */
	public function traineeListAction(){
		// let simon pass  trainee
		
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stLog = new Model_Hr_Traineelog();
		$mail = new Model_Emailshandler();
		if($_POST){
			
			//d($_POST);
			//step 1 check password 
			$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['password']));
			if(!$stLine){
				echo "<h1>Incorrect Password,Verify Your Password and Try Again</h1>";
			}else{
				if($stLine['id'] == 110 || $stLine['id'] == 4 ){
					// pass
					if(isset($_POST['btn_pass'])){

						foreach($_POST['btn_pass'] as $id => $v){

							$stInfo->updatePosition($id,2);
							$sdLine = $stDetail->getDetail($id);
							
							// if pass trainee and the is not never expire , extend the expire date 
							$expDate = $stLine['expire_date'];
							
							$mailbody = "Staff ".$sdLine['ni'].", ID[".$id."] has passed the traning period,the current position is part time.This is just a notice ,you need to do nothing.";
							$mailbodyAcc = "Simon has Pass a new trainee".$sdLine['ni'].", ID[".$id."], the current position has been changed to part time.";
							$subject = "Trainee Pass Trainning Peroid";
							
							if($expDate != '2037-12-31'){
								
								$newExpDate = Model_DatetimeHelper::adjustYears("add",Model_DatetimeHelper::dateToday(),1);
								$stDetail->updateExpireDate($newExpDate, $id);	
								
								$mailbodyAcc .= "The staff still did not submit all Paper Document, please double check the document list for the staff, if everything is ready, please go to click 'never expire'";
								$mailbodyAcc .= "Other wise, PLEASE MUST FOLLOW UP THIS CASE.";
								$subject .=",Still Need Document, Please follow Up";
								$mail->sendActionEmail("payroll@phonecollection.com.au",$subject,$mailbodyAcc);
							}
							else{
								
								$mailbodyAcc .= "This is just a notice ,you need to do nothing.";
								$mail->sendNormalEmail("payroll@phonecollection.com.au",$subject,$mailbodyAcc);
							}
							
							
							$mail->sendNormalEmail("simon.seop@phonecollection.com.au;office@phonecollection.com.au", $subject, $mailbody);
							

							
							$stLog->addTraineelog($id, $stLine['id'], Model_DatetimeHelper::dateToday(), Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(),2);
						}
					}
					// not pass
					if(isset($_POST['btn_not_pass'])){
						
						// change posion to not pass
						// password expire in 7 days
						
						foreach($_POST['btn_not_pass'] as $id => $v){

							$stInfo->updatePosition($id,99);
							$sdLine = $stDetail->getDetail($id);
							$dateExpire = Model_DatetimeHelper::adjustDays("add",Model_DatetimeHelper::dateToday(),1);
							 
							
							$stDetail->updateExpireDate($dateExpire, $id);
							$stInfo->updateLeave($id,9, $dateExpire);
							
							$subject = "Trainee Failed Trainning Peroid";
							$mailbody = "Staff ".$sdLine['ni'].", ID[".$id."] failed trainning, the password will be expire in 7 days, please contact manager to arrange final roster and leave date ";
							$mail->sendNormalEmail("office@phonecollection.com.au;payroll@phonecollection.com.au", $subject, $mailbody);
							$stLog->addTraineelog($id, $stLine['id'], Model_DatetimeHelper::dateToday(), Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(),99);
							
						}
						
					}
				}
			else{
				
				echo "<h1>You Do Not Have Permission To Chanage The Trainee Position!</h1>";
					
				}
			}
			
			
		}
		
		$stList = $stInfo->listAllTrainee();
		$this->view->stList = $stList;
		
		$this->view->history = $stLog->listAll();
		
		//d($stList);
	}
	
	/**
	 * This funcion is done but not in good use 
	 */
	public function checkMyTaskAction(){
		
		$idStaff = $this->_getParam("id_staff");
		
		$taskHistory = new Model_Hr_Taskhistory();
		
		$task = new Model_Hr_Tasklist();
		
		if($_POST){
			
			$taskHistory->finishTaskSimple($_POST['id_task_history']);
			
		}
		
		
		
		
		$tList = $taskHistory->listTaskByStaff($idStaff);
		//d($tList);
		$arrRes = array();
		
		foreach($tList as $tRow){

			$tmpArr = array();
			$tmpArr = $tRow;
			$idTask = $tRow["id_task"];
			$tdLine = $task->getTasklist($idTask);
			$tmpArr = array_merge($tmpArr,$tdLine);
			
			$arrRes[] = $tmpArr;
		}
		
		$this->view->tList = $arrRes;
		$this->view->dateToday = Model_DatetimeHelper::dateToday();
		
		
		
	}
	
	/**
	 * this function is for manager to download unconfirm roster 
	 */
	public function downloadUnconfirmedRosterAction(){
		
		$idMgr = $this->_getParam("id_mgr");
		$token = $this->_getParam("token");
		
		$this->view->idMgr = $idMgr;
		$this->view->token = $token;
		
		
		$etlLog = new Model_Payroll_Etllog();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$arrMgr = unserialize(ARR_MANAGER);
		
		
		
		if($idMgr != "" && base64_encode($idMgr) == $token){
			$this->view->showpassword = false;
			//list staff and cycle pag 
			if($idMgr == 110 || $idMgr == 4) {
				$res = $etlLog->listStaffEtlByManager(0);
					
				$arrCycle = array();
				$arrStaff = array();
				$arrStDetail = array();
				$arrRes = array();
					
				foreach($res as $k => $v){
					$arrStaff[] = $v['id_staff'];
					$arrCycle[] = trim($v['id_cycle'])."-".trim($v['year']);
					$arrRes[$v['id_staff']][$v['id_cycle']."-".$v['year']] = $v;
				}
					
				$arrStaff = array_unique($arrStaff);
				$arrCycle = array_unique($arrCycle);
				sort($arrStaff);
				sort($arrCycle);
					
				foreach($arrStaff as $id){
				
					$stLine = $stDetail->getDetail($id);
					$stManager = $stInfo->getStaffinfo($id);
					$sortManager[] = $stManager['id_manger_belong'];
					$arrStDetail[$id]['name'] = $stLine['ni'].' ['.ucwords(Model_EncryptHelper::getSslPassword($stLine['n'])).']';
					$arrStDetail[$id]['manager'] = $stManager['id_manger_belong'];
					$arrStDetail[$id]['id'] = $id;
				}
				
				array_multisort($sortManager,SORT_ASC,$arrStDetail);
				$this->view->arrCycle = $arrCycle;
				$this->view->arrStaff = $arrStaff;
				$this->view->arrStDetail = $arrStDetail;
				$this->view->arrRes = $arrRes;
			}else{
			$res = $etlLog->listStaffEtlByManager($idMgr);
			
			$arrCycle = array();
			$arrStaff = array();
			$arrStDetail = array();
			$arrRes = array();
			
			foreach($res as $k => $v){
				$arrStaff[] = $v['id_staff'];
				$arrCycle[] = trim($v['id_cycle'])."-".trim($v['year']);
				$arrRes[$v['id_staff']][$v['id_cycle']."-".$v['year']] = $v;
			}
			
			$arrStaff = array_unique($arrStaff);
			$arrCycle = array_unique($arrCycle);
			sort($arrStaff);
			sort($arrCycle);
			$sortManager = array();
			foreach($arrStaff as $id){
				
				$stLine = $stDetail->getDetail($id);
					$stManager = $stInfo->getStaffinfo($id);
					$arrStDetail[$id]['name'] = $stLine['ni'].' ['.ucwords(Model_EncryptHelper::getSslPassword($stLine['n'])).']';
					$arrStDetail[$id]['manager'] = $stManager['id_manger_belong'];
					$arrStDetail[$id]['id'] = $id;
			}
			
			$this->view->arrCycle = $arrCycle;
			$this->view->arrStaff = $arrStaff;
			$this->view->arrStDetail = $arrStDetail;
			$this->view->arrRes = $arrRes;
			
			//d($arrCycle,$arrStDetail,$arrRes);
			}
		}
		else{
			
			$this->view->showpassword = true;
		}
		
		if($_POST){
			
			if(isset($_POST['btn_check'])){
				$password = $_POST['password'];
				$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($password));
			
				if($stLine['id'] && isset($arrMgr[$stLine['id']])){
				
					$idMgr = $stLine['id']; 
				
					$url = "/roster/download-unconfirmed-roster/id_mgr/".$idMgr."/token/".base64_encode($idMgr);  
				
					$this->_redirect($url);																	
				
				}
			}
			
			if(isset($_POST['submit'])){

				foreach ($_POST['submit'] as $k => $v){
					$stInfo->deleteManager($k);
				}
				$url = "/roster/download-unconfirmed-roster/id_mgr/".$idMgr."/token/".base64_encode($idMgr);
				
				$this->_redirect($url);
			}
			
		}
		
		
	
	}
	
	/**
	 * when manager scan the unconfirm roter 
	 * it means the staff has signed on the unconfirm roster and it is ready to send back to warehouse  
	 */
	
	public function managerScanEtlPaperAction(){
		
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		$arrRes = array();
		
		$idMgr = $this->_getParam("id_mgr");
		$token = $this->_getParam("token");
		
		
		if($_POST){
				
			$arrRes = unserialize(base64_decode($_POST['str_res']));
			$arrBc = explode('-', trim($_POST['barcode']));
			if($arrBc[0] >0 && isset($arrBc[1]) && isset($arrBc[2])){
					
				$stDetailLine  = $stDetail->getDetail($arrBc[0]);
				$fullName = Model_EncryptHelper::getSslPassword($stDetailLine['n']);
				$nickName = $stDetailLine['ni'];
					
				$log = new Model_Payroll_Etllog();
				$year = '20'.$arrBc[2];
				$timeNow = Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow();
		
				//$log->addEtllog($arrBc[0], $arrBc[1], $year, $timeNow);
				
				if($token == base64_encode($idMgr)){
				$log->managerUpdateLog($arrBc[0], $arrBc[1], $year, $idMgr, $timeNow);
				$arrRes[] = array($arrBc[0],$fullName,$nickName,$arrBc[1],$timeNow,$year);
				}
			}else if ($arrBc[0] == 'S' && isset($arrBc[1]) && isset($arrBc[2]) && isset($arrBc[3])){
					
				$stDetailLine  = $stDetail->getDetail($arrBc[1]);
				$fullName = Model_EncryptHelper::getSslPassword($stDetailLine['n']);
				$nickName = $stDetailLine['ni'];
					
				$log = new Model_Payroll_Etllog();
				$year = '20'.$arrBc[3];
				$timeNow = Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow();

				if($token == base64_encode($idMgr)){
				$log->managerUpdateLog($arrBc[1], $arrBc[2], $year, $idMgr, $timeNow,1);
				$arrRes[] = array($arrBc[1],$fullName,$nickName,$arrBc[2],$timeNow,$year);
				}
			}
			
		}
		
		$this->view->arrRes = $arrRes;
		$this->view->strRes = base64_encode(serialize($arrRes));
	}
	
	public function downloadEtlPaperAction(){
		
		$fileName = $this->_getParam("f_name");
		
	}
	/**
	 * check the staff is not never expire and not trainee and not levave,staff name should be notice to simon every 3 days.
	 * Add By Norman, Check missing Document ,
	 */
	public function checkStaffMissingDocumentAction(){
		
		// 
		// run on monday and thursday
		
		$ifEmail = $this->_getParam('email');
		$this->view->ifemail = $ifEmail;
		
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		$posCategory = new Model_Hr_Staffposition();
		
		
		$stList = $stDetail->listStaff();
		
		$arrRes = array();
		
		
		foreach($stList as $k => $v){
			
			// check expire date 
			$expDate = $v['expire_date'];
			if($expDate != '2037-12-31'){
				//check position and leave 
				$stInfoLine = $stInfo->getStaffinfo($v['id']);
				if($stInfoLine){
					if($stInfoLine['leave'] != 9 ){
						if($stInfoLine['position_status'] != 1){
							$staffName = Model_EncryptHelper::getSslPassword($v['n']);
							$staffNick = $v['ni'];
							$shList = $attRecord->getShopHeadByStaffId($v['id']);
							$strShop = '';
							foreach($shList as $sh){
								
								$strShop .= Model_EncryptHelper::getSslPassword($sh['sh']).",";
							}
							$regDate = $stInfoLine['register_date'];
							$expireDate = $v['expire_date'];
							$pos = $posCategory->getStaffposition($stInfoLine['position_status']);
							$arrRes[] = array($staffName,$staffNick,$strShop,$regDate,$expireDate,$pos['title_position']);
						}
					}	
					
				}
					
			}
		}
		
		$this->view->arrRes = $arrRes;
		
	}
	
}
?>